Você está na página 1de 52

WHY PL/SQL??

• SQL IS A 4 GL TOOL
Meaning it uses constructs and elements that specify "what to do"
without having to specify "how to do it."

• PURPOSE OF SQL
DDL,DML,CONTROL,QUERYING

• PURPOSE OF 3 GL TOOLS
USES constructs, such as conditional or iterative execution etc.
(logic & control flow)

• PL/SQL
To accommodate 3GL features as a procedural extension to SQL
Bridges the gap b/w database and programming languages.
PL/SQL vs Other 3GLs
FEATURE PL/SQL OTHER 3GLS (JAVA, C++, C)
Ease of use Fairly easy Difficult; requires a steep learning
curve
Portability of Highly portable Portable except for system calls
applications
Integration with Tightly Integrated to a lesser degree than
SQL integrated PL/SQL; access by means of SQLJ or
JDBC
SQL-intensive Well suited Not well suited
operations
Compute- Not well suited Well suited (e.g., for sorting of large
intensive arrays)
operations
Object orientation Object oriented Truly object oriented (like Java and
to a certain C++)
extent
HISTORY OF PL/SQL
PL/SQL was first introduced in 1991 with Oracle 6.0. It
was provided as the "procedural option" on the server side. At
the same time, it was subsequently introduced on the client
side with SQL*Forms version 3.0 having a PL/SQL engine of its
own. The first version of PL/SQL, PL/SQL 1.0, had very limited
procedural features. But one of its strong points was its
capability to process multiple SQL statements mixed with
procedural constructs.
PL/SQL has its roots in ADA, a high-level programming
language. The concept of the PL/SQL block resembles the
concept of block structure in ADA using BEGIN and END
blocks. PL/SQL shares other features with ADA such as the
syntax "=" used for comparison and ":=" used for assignment,
exception handling, and the declarative syntax of defining
stored subprograms.
Over the years, Oracle came up with new releases of PL/SQL. With
Oracle 7.0, Oracle released PL/SQL 2.0, which turned Oracle into an
active database with the capability to store business and application
logic in the database in the form of stored procedures, functions, and
packages. It also defined the capability to declare programmer-
defined records and arrays in the form of PL/SQL tables. PL/SQL 2.1
came into existence with Oracle 7.1 and enabled the use of stored
functions in SQL statements. Also, dynamic SQL was introduced in
PL/SQL for the first time with the DBMS_SQL package. Oracle 7.2
was released subsequently, and along with it came PL/SQL 2.2. It
had the capability to define binary wrappers for PL/SQL stored
subprograms, thus hiding code from other developers. Also, the
DBMS_JOB package was introduced, which enabled programmers to
submit jobs from within the database. The next release of PL/SQL
was PL/SQL 2.3, which was introduced with Oracle 7.3. It enhanced
the capabilities of PL/SQL tables with the ability to define new
methods, and it also enabled programmers to access the file system
from within the database. File I/O could be done using the UTL_FILE
package.
Oracle 8.x was a major breakthrough in the Oracle
database history with the introduction of objects and Java in
the database. PL/SQL 8.x was released along with Oracle
8.x and included major features such as native dynamic
SQL, Java stored procedures, and system- and schema-level
database triggers.

Finally, Oracle9i was released and along with it came


PL/SQL 9.2 and 9.0, corresponding to Releases 2 and 1 of
Oracle9i. This release saw the introduction of native
compilation of PL/SQL code, enhancement to PL/SQL
cursors in the form of cursor expressions, new data types,
enhancements to bulk binding, pipelined table functions, true
inheritance among objects, and more.
ADVANTAGES OF PL/SQL
• Procedural capabilities
To define and implement 3GL constructs with embedded SQL statements.

• Portability
Programs written in PL/SQL are hardware independent and operating system

independent. (oracle server+IDE)

• Modularity
Write independent programming modules with procedures/functions/
packages
• Better Performance
Data type conversion isn't needed on input and output.
Network traffic is reduced

• OBJECT ORIENTATION
Oracle database and corresponding PL/SQL versions

ORACLE PL-SQL CHARACTERISTICS


RELEASE VERSION
6.0 1.0 Initial version, used as scripting language in sql plus and a programming
language in sql forms 3.
7.0 2.0 Added support for stored procedures, functions, packages, programmer-
defined records, PL/SQL tables, and many package extensions.
7.1 2.1 Supported programmer-defined subtypes, enabled the use of stored
functions inside SQL statements, and offered dynamic SQL with the
DBMS_SQL package. With PL/SQL 2.1, you could execute SQL DDL
statements from within PL/SQL programs.
7.2 2.2 It had the capability to define binary wrappers for PL/SQL stored
subprograms, thus hiding code from other developers. Also, the
DBMS_JOB package was introduced, which enabled programmers to
submit jobs from within the database.
7.3 2.3 Enhanced functionality of PL/SQL tables, offered improved remote
dependency management, added file I/O capabilities to PL/SQL with the
UTL_FILE package, and completed the implementation of cursor
variables.
Oracle database and corresponding PL/SQL versions

ORACLE PL-SQL CHARACTERISTICS


RELEASE VERSION
8.0 8.0 Reflected Oracle's effort to synchronize version numbers across related
products. PL/SQL 8.0 is the version of PL/SQL that supported
enhancements of Oracle8 Database, including large objects (LOBs),
object-oriented design and development, collections (VARRAYs and
nested tables), and Oracle/AQ (the Oracle/Advanced Queuing facility).
8.1 8.1 The first of Oracle's i series, the corresponding release of PL/SQL
offered a truly impressive set of added functionality, including a new
version of dynamic SQL, support for Java in the database, the invoker
rights model, the execution authority option, autonomous transactions,
and high-performance "bulk" DML and queries.
9.1 9.1 The first release of this version included support for inheritance in object
types, table functions and cursor expressions (allowing for parallelization
of PL/SQL function execution), multilevel collections and the CASE
statement and CASE expression.
9.2 9.2 Oracle9i Database Release 2 put a major emphasis on XML (Extensible
Markup Language) but also had some treats for PL/SQL developers,
including associative arrays that can be indexed by VARCHAR2 strings
in addition to integers, record-based DML (allowing you to perform an
insert using a record, for example), and many improvements to
UTL_FILE (which allows you to read/write files from within a PL/SQL
program).
PL/SQL Environment

PL/SQL engine
PL/SQL Procedural
PL/SQL PL/SQL
SQL statement
block block
executor

SQL statement executor

Oracle server
BLOCK

• Basic coding element

• A discrete set of code performing function

• Consists of

 Declaration section(optional)
 Execution section
 Exception Section(optional)
TYPES OF BLOCK

• Anonymous block

• Named block
BLOCK SECTIONS
DECLARATION IDENTIFIERS
CURSORS
EXCEPTIONS
EXECUTABLE
STATEMENTS EXECUTION

EXCEPTION EXCEPTION
HANDLERS
VARIABLES
Temporarily Stores Data

Manipulation of stored values

Reusable

Variable Name Maximum length of 30

No white spaces

Begin with an alphabet

One variable per line


VARIABLES
DO’S DONT’S

VNO INT;
1NO INT;

VNAME VARCHAR2(20); VNAME VARCHAR2(20),VDATE DATE;

VEMPNO NUMBER(4); VEMPNO,VDEPTNO NUMBER(4);

V_NO INT :=101; V_NO INT=1;

V NAM CHAR(1);
V/NAME VARCHAR2(10);
SAMPLE BLOCK
PROCEDURE
BEGIN

DBMS_OUTPUT . PUT_LINE('HELLO WORLD');

END;

TERMINATOR
OUTPUT
PL/SQL procedure successfully completed.

IN ORDER TO SEE THE OUTPUT USE

SET SERVEROUT ON
BLOCK WITH VARIABLES

DECLARE

V_MSG VARCHAR2(50):=‘HELLO WORLD’;

BEGIN

DBMS_OUTPUT . PUT_LINE(V_MSG);

END;
BLOCK FOR SELCTING TABLE COLUMN

DECLARE

V_NAME VARCHAR2(10);

BEGIN
SELECT ENAME
INTO V_NAME
FROM EMP
WHERE EMPNO=7369;
DBMS_OUTPUT . PUT_LINE(V_NAME);
END;
GOLDEN RULES OF EXECUTION SECTION
SELECT SHOULD HAVE AN INTO CLAUSE

QUERY SHOULD RETURN SINGLE ROW

DECLARE

V_NAME VARCHAR2(10);

BEGIN
SELECT ENAME
INTO V_NAME
FROM EMP
WHERE EMPNO=7369;

DBMS_OUTPUT . PUT_LINE(V_NAME);
END;
DML OPERATIONS USING PL/SQL
SQL> create table e2 as select empno,ename from emp;
Table created.
SQL> declare
v_no emp.empno%type;
v_name emp.ename%type;
begin
insert into e2 values(1,'xyz');
end;
/
PL/SQL procedure successfully completed.
SQL> select * from e2;
EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER

1 xyz
15 rows selected.
DML OPERATIONS USING PL/SQL
SQL> declare
v_eno e2.empno%type :=1;v_ename e2.ename%type :='RAMU';
begin
update e2 set ename=V_ENAME WHERE EMPNO=V_ENO;
END;
/
SQL> SELECT * FROM E2;

EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
1 RAMU
DML OPERATIONS USING PL/SQL
SQL> declare
v_eno e2.empno%type :=1;
begin
Delete from emp WHERE EMPNO=V_ENO;
END;
/
SQL> SELECT * FROM E2;

EMPNO ENAME
---------- ----------
7369 SMITH
7499 ALLEN
7521 WARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
7900 JAMES
7902 FORD
7934 MILLER
Procedural constructs

• Conditional constructs
if elsif else
CASE

• Iterative constructs

• simple loop
• numeric for loop
• while loop
• nested loops
If elsif else

DECLARE
a number := 50;
b number := -20;
BEGIN
IF (a>b) THEN
dbms_output.put_line('A is greater than B');
ELSIF (a<b) THEN
dbms_output.put_line('A is less than B');
ELSE
dbms_output.put_line('A is equal to B');
END IF;
END;
SIMPLE LOOP

DECLARE
line_length NUMBER := 50;
separator VARCHAR2(1) := '=';
actual_line VARCHAR2(150);
i NUMBER := 1;
BEGIN
LOOP
actual_line := actual_line || separator;
EXIT WHEN i = line_length;
i:= i + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE(actual_line);
END;
/
WHILE LOOP

DECLARE
line_length NUMBER := 50;
separator VARCHAR2(1) := '=';
actual_line VARCHAR2(150);
idx NUMBER := 1;
BEGIN
WHILE (idx<=line_length) LOOP
actual_line := actual_line || separator;
idx := idx +1 ;
END LOOP;
DBMS_OUTPUT.PUT_LINE(actual_line);
END;
FOR LOOP

DECLARE
line_length NUMBER := 50;
separator VARCHAR2(1) := '=';
actual_line VARCHAR2(150);
BEGIN
FOR idx in 1..line_length LOOP
actual_line := actual_line || separator;
END LOOP;
DBMS_OUTPUT.PUT_LINE(actual_line);
END;
Block Structure for Anonymous PL/SQL
Blocks

DECLARE (optional)
Declare PL/SQL objects to be used
within this block
BEGIN (mandatory)
Define the executable statements
EXCEPTION (optional)
Define the actions that take place if
an error arises
END; (mandatory)
Block Structure for PL/SQL
Subprograms

Header
IS|AS
Declaration section
BEGIN
Executable section
EXCEPTION (optional)
Exception section
END;
PL/SQL ENVIRONMENT

• Development

• Execution

• Debugging

SQL*Plus and Procedure Builder are used for all above


Use of Variables

Variables can be used for:


• Temporary storage of data
• Manipulation of stored values
• Reusability
• Ease of maintenance
Handling Variables in PL/SQL

• Declare and initialize variables in the


declaration section.
• Assign new values to variables in the
executable section.
• Pass values into PL/SQL blocks
through parameters.
• View results through output variables.
Types of Variables

• PL/SQL variables:
– Scalar
– Composite
– Reference
– LOB (large objects)
• Non-PL/SQL variables: Bind and host
variables
Guidelines for Declaring PL/SQL
Variables
• Follow naming conventions.
• Initialize variables designated as NOT
NULL and CONSTANT.
• Declare one identifier per line.
• Initialize identifiers by using the
assignment operator (:=) or the
DEFAULT reserved word.
identifier := expr;
Naming Rules
• Two variables can have the same name,
provided they are in different blocks.
• The variable name (identifier) should not be
the same as the name of table columns used
in the block.
DECLARE
employee_id NUMBER(6);
BEGIN
SELECT employee_id
INTO employee_id
FROM employees
WHERE last_name = 'Kochhar';
END;
/
Variable Initialization and Keywords

• Assignment operator (:=)


• DEFAULT keyword
• NOT NULL constraint
Syntax:
identifier := expr;

Examples:
v_hiredate := '01-JAN-2001';

v_ename := 'Maduro';
Scalar Data Types

• Hold a single value


• Have no internal components

25-OCT-99
“Four score and seven years
TRUE
ago our fathers brought
forth upon this continent, a
new nation, conceived in
256120.08 LIBERTY, and dedicated to
the proposition that all men

Atlanta
are created equal.”
Base Scalar Data Types

• CHAR [(maximum_length)]
• VARCHAR2 (maximum_length)
• LONG
• LONG RAW
• NUMBER [(precision, scale)]
• BINARY_INTEGER
• PLS_INTEGER
• BOOLEAN
Base Scalar Data Types

• DATE
• TIMESTAMP
• TIMESTAMP WITH TIME ZONE
• TIMESTAMP WITH LOCAL TIME
ZONE
• INTERVAL YEAR TO MONTH
• INTERVAL DAY TO SECOND
Scalar Variable Declarations

Examples:
DECLARE
v_job VARCHAR2(9);
v_count BINARY_INTEGER := 0;
v_total_sal NUMBER(9,2) := 0;
v_orderdate DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
v_valid BOOLEAN NOT NULL := TRUE;
...
The %TYPE Attribute

• Declare a variable according to:


– A database column definition
– Another previously declared variable
• Prefix %TYPE with:
– The database table and column
– The previously declared variable name
Declaring Variables
with the %TYPE Attribute
Syntax:
identifier Table.column_name%TYPE;

Examples:
...
v_name employees.last_name%TYPE;
v_balance NUMBER(7,2);
v_min_balance v_balance%TYPE := 10;
...
Declaring Boolean Variables
• Only the values TRUE, FALSE, and
NULL can be assigned to a Boolean
variable.
• The variables are compared by the
logical operators AND, OR, and NOT.
• The variables always yield TRUE,
FALSE, or NULL.
• Arithmetic, character, and date
expressions can be used to return a
Boolean value.
Using Bind Variables

To reference a bind variable in PL/SQL,


you must prefix its name with a colon
(:).
Example:
VARIABLE g_salary NUMBER
BEGIN
SELECT salary
INTO :g_salary
FROM employees
WHERE employee_id = 178;
END;
/
PRINT g_salary
Referencing Non-PL/SQL Variables

Store the annual salary into a


iSQL*Plus host variable.
:g_monthly_sal := v_sal / 12;

• Reference non-PL/SQL variables as


host variables.
• Prefix the references with a colon (:).
DBMS_OUTPUT.PUT_LINE
• An Oracle-supplied packaged procedure
• An alternative for displaying data from a PL/SQL block
• Must be enabled in iSQL*Plus with
SET SERVEROUTPUT ON

SET SERVEROUTPUT ON
DEFINE p_annual_sal = 60000

DECLARE
v_sal NUMBER(9,2) := &p_annual_sal;
BEGIN
v_sal := v_sal/12;
DBMS_OUTPUT.PUT_LINE ('The monthly salary is ' ||
TO_CHAR(v_sal));
END;
/
SELECT Statements in PL/SQL
• The INTO clause is required.
• Queries must return one and only one
row.
DECLARE
• Example:
v_deptno NUMBER(4);
v_location_id NUMBER(4);
BEGIN
SELECT department_id, location_id
INTO v_deptno, v_location_id
FROM departments
WHERE department_name = 'Sales';
...
END;
/
RETRIEVING DATA IN PL/SQL

DECLARE
v_hire_date emp.hiredate%TYPE;
v_sal emp.sal%TYPE;
BEGIN
SELECT hire_date, sal
INTO v_hire_date, v_sal
FROM emp
WHERE employee_id = 100;
...
END;
/
RETRIEVING DATA IN PL/SQL

SET SERVEROUTPUT ON
DECLARE
v_sum_sal NUMBER(10,2);
v_deptno NUMBER NOT NULL := 60;
BEGIN
SELECT SUM(sal) -- group function
INTO v_sum_sal
FROM emp
WHERE dept_id = v_deptno;
DBMS_OUTPUT.PUT_LINE ('The sum sal is ' ||
TO_CHAR(v_sum_sal));
END;
/
1. What are the four keywords of the basic PL/SQL block? What happens in each area?
[DECLARE
Declare local variables
]BEGIN
Executable statements
[EXCEPTION
Error handling statements
]END;

2. What must each executable statement end with?


; (Semi-colon)

3. What is the syntax to declare a variable?


variable_name DATATYPE [:=] [NOT NULL];

4. What is the syntax to declare a constant?


constant_name CONSTANT DATATYPE := ;

5.What is the syntax to declare a cursor?


CURSOR cursor_name IS SELECT statement ;

6.What is the syntax to declare an exception?


exception_name EXCEPTION;

7.How do you link this exception with a known Oracle error?


PRAGMA EXCEPTION_INIT (exception_name, ERROR_NUMBER);

8. What symbol do you use to assign values to variables?


:=
The following strings are valid names of identifiers:

• company_id#
• primary_acct_responsibility
• First_Name
• FirstName
• address_line1
• S123456
The following identifiers are all illegal in PL/SQL:

• 1st_year -- Doesn't start with a letter


• procedure-name -- Contains invalid character "-"
• minimum_%_due -- Contains invalid character "%"
• maximum_value_exploded_for_detail -- Too long
• company ID -- Has embedded whitespace

Você também pode gostar