PL/SQL
PL/SQL
Overview of PL/SQL
• With PL/SQL, you can use SQL statements to
manipulate ORACLE data and flow-of-control
statements to process the data.
• can declare constants and variables, define
subprograms (procedures and functions), and
trap runtime errors.
• PL/SQL combines the data manipulating
power of SQL with the data processing power
of procedural languages.
Overview of PL/SQL cont..
• PL/SQL is a block-structured language.
DECLARE
-- Declarations
BEGIN
-- Statements
EXCEPTION
-- Handlers
• END;
The PL/SQL Block
• All PL/SQL programs are made up of Blocks. A
• PL/SQL program MUST contain at least one block.
A
• Block is made up of PL/SQL statements enclosed
• within the keywords, BEGIN and END, for
example:-
• BEGIN
• INSERT INTO table (col) VALUES ('XX');
• END;
The PL/SQL Block
Multiple Blocks
• A PL/SQL program can consist of several in-line
• blocks, for example:-
• DECLARE
• v_number NUMBER;
• BEGIN
• v_number := 10;
• EXCEPTION
• WHEN OTHERS THEN
• DBMS_OUTPUT.put_line('Error 1');
• END;
• BEGIN
• v_number := 20;
• EXCEPTION
• WHEN OTHERS THEN
• DBMS_OUTPUT.put_line('Error 2');
• END;
• BEGIN
• v_number := 20;
• EXCEPTION
• WHEN OTHERS THEN
• DBMS_OUTPUT.put_line('Error 3');
The PL/SQL Block
Multiple Blocks cont..
The PL/SQL Block
Nested Blocks
The PL/SQL Block
Block Types
• PL/SQL Engine
• It is a separator,which splits the SQL and PL/SQL
statements.PL/SQL block comprises of SQL &PL
commands are submitted as one request.PL/SQL
engine split the block and sends appropriated
commands to the corresponding units.SQL
evaluator will handle SQL statements(available on
the server side).PL Evaulator to handle PL
commands.Engine can reside either in client side or
in the server side.
PL/SQL Arch …
Using DEFAULT
• You can use the keyword DEFAULT instead of the assignment operator to initialize
• variables. For example, the declaration
• blood_type CHAR := 'O';
• can be rewritten as follows:
• blood_type CHAR DEFAULT 'O';
• Use DEFAULT for variables that have a typical value. Use the assignment operator
for
• variables (such as counters and accumulators) that have no typical value. For
example:
• hours_worked INTEGER DEFAULT 40;
• employee_count INTEGER := 0;
• You can also use DEFAULT to initialize subprogram parameters, cursor parameters,
• and fields in a user-defined record.
Using NOT NULL
• Besides assigning an initial value, declarations
can impose the NOT NULL constraint:
• DECLARE
• acct_id INTEGER(4) NOT NULL := 9999;
• You cannot assign nulls to a variable defined as
NOT NULL. If you try, PL/SQL raises
• the predefined exception VALUE_ERROR.
• The NOT NULL constraint must be followed by
an initialization clause
Using the %TYPE Attribute
• The %TYPE attribute provides the datatype of a
variable or database column. In the
• following example, %TYPE provides the
datatype of a variable:
• DECLARE
• credit NUMBER(7,2);
• debit credit%TYPE;
• %TYPE variables do not inherit the NOT NULL
column constraint
PL/SQL Records
• Declaring a record:
• TYPE record_type_name IS RECORD
(first_col_name column_datatype,
second_col_name column_datatype);
What are records Cont…
BEGIN
IF sales > 50000 THEN
bonus := 1500;
ELSIF sales > 35000 THEN
bonus := 500;
ELSE
bonus := 100;
END IF;
INSERT INTO payroll VALUES (emp_id, bonus, ...);
END;
Case Statement
• DECLARE
• grade VARCHAR2(12) :='A';
• BEGIN
• CASE grade
• WHEN 'A' THEN dbms_output.put_line('Excellent');
• WHEN 'B' THEN dbms_output.put_line('Very Good');
• WHEN 'C' THEN dbms_output.put_line('Good');
• WHEN 'D' THEN dbms_output.put_line('Fair');
• WHEN 'F' THEN dbms_output.put_line('Poor');
• ELSE dbms_output.put_line('No such grade');
• END CASE;
• * END;
Iterative Statements in PL/SQL
• FOR counter IN val1..val2 LOOP statements; END LOOP; val1 - Start integer value.
• val2 - End integer value.
• Important steps to follow when executing a while loop:
1) The counter variable is implicitly declared in the declaration section, so it's
not necessary to declare it explicity.
2) The counter variable is incremented by 1 and does not need to be
incremented explicitly.
3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's
not done oftenly.
CURSOR
• E.g.
BEGIN
IF NOT emp_cur %ISOPEN THEN
OPEN emp_cur ;
END IF;
LOOP
FETCH emp_cur INTO emp_rec;
EXIT WHEN emp_cur%NOTFOUND;
dbms_output.put_line(emp_cur r.ename || ' ' ||emp_cur.sal || ' ' ||
emp_cur.mgr);
END LOOP;
END;
While Loop with Explicit Cursors
DECLARE
CURSOR emp_cur
IS SELECT ename, sal FROM emp;
emp_rec emp_cur%rowtype;
BEGIN
OPEN emp_cur;
DECLARE
CURSOR emp_cur IS
SELECT ename, sal FROM emp;
BEGIN
FOR emp_rec in emp_cur LOOP
dbms_output.put_line(emp_rec.ename || ' '
||emp_rec.sal);
END LOOP;
END
Passing Parameters
• DECLARE
• CURSOR emp_cur IS
• SELECT sal FROM emp
• WHERE deptno=10
• FOR UPDATE OF sal NOWAIT ;
• emp_record emp_cur%rowtype;
• BEGIN
• FOR emp_record in emp_cur
• LOOP
• UPDATE emp
• set sal = 1200
• WHERE CURRENT OF emp_cur;
• END LOOP;
• END;
• /SELECT ename,sal FROM emp WHERE deptno=30;
Cont …
• The Where Current of clause in UPDATE and Delete
statement states that the most recent row fetched
from the table should be updated or deleted.
• It must has to be declare with cursor and with FOR
UPDATE.
• When the session opens a cursor with the FOR
UPDATE clause, all rows in the return seet will hold
row level exclusive locks. Other sessions can only
query the rows but they can not update, delete or
select with FOR UPDATE
REF Cursor
• A ref cursor in Oracle PL/SQL is much like an
ordinary PL/SQL cursor in that it acts as a
pointer to the result set of the cursor with
which it is associated. However, the difference
is that a ref cursor can be assigned to different
result sets whereas a cursor is always
associated with the same result set. Cursors
and ref cursors are not interchangeable.
• A Ref cursor is a variable, defined as a cursor type which will point or reference result set.
The advantages of ref cursor has over a plain cursor is that it can be passed as variable to
procedure or functions.
• The ref cursor cab assigned to the ref cursor variables.
• The ref cursor variable is not a cursor, but a variable that points to a cursor.
• Before assigning a ref cursor, you must declare a cursor type must be declared.
• The “Ref Cursor” weak typed cursor variable because it doesn’t define data type which data
type will return.
Cont….
• The real purpose of ref cursors is to be able to share cursors and result sets between the client
and the Oracle server or between different subroutines. For example you might open a cursor
in an Oracle Forms client and then continue working with the cursor on the server or you might
open a cursor in say a Java program and then continue working with it in a PL/SQL stored
procedure.
Ref cursors also come in two variants: strongly typed and weakly typed depending on how likely
you are (or want to) reuse a cursor variable. Weak ref cursor types can be associated with any
query whereas strong ref cursor types can only be associated with cursors of the same type.
• The most important benefit of the cursor variable is that it provides a mechanism for passing
results of queries (the rows returned by fetches against a cursor) between different PL/SQL
programs -- even between client and server PL/SQL programs. Prior to PL/SQL Release 2.3, you
would have had to fetch all data from the cursor, store it in PL/SQL variables (perhaps a PL/SQL
table), and then pass those variables as arguments. With cursor variables, you simply pass the
reference to that cursor. This improves performance and streamlines your code.
• declare
• type r_cursor is REF CURSOR;
• c_emp r_cursor;
• er emp%rowtype;
• begin
• open c_emp for select * from emp;
• loop
• fetch c_emp into er;
• exit when c_emp%notfound;
• dbms_output.put_line(er.ename || ' - ' || er.sal);
• end loop;
• close c_emp;
• end;
• Usage Restrictions
• The following are restrictions on cursor variable usage.
• 1. Comparison operators cannot be used to test cursor variables for equality, inequality, null, or not null.
• 2. Null cannot be assigned to a cursor variable.
• 3. The value of a cursor variable cannot be stored in a database column.
• 4. Static cursors and cursor variables are not interchangeable. For example, a static cursor cannot be used in an
OPEN FOR statement.
• Cursor variables cannot be declared in a package since they do not have a persistent state.
• You cannot use RPCs (Remote Procedure Calls) to pass cursor variables from one server to another.
• If you pass a cursor variable as a bind or host variable to PL/SQL, you will not be able to fetch from it from within the
server unless you also open it in that same server call.
• The query you associate with a cursor variable in an OPEN-FOR statement cannot use the FOR UPDATE clause.
• You cannot test for cursor variable equality, inequality, or nullity using comparison operators.
• You cannot assign NULLs to a cursor variable.
• Database columns cannot store cursor variable values. You will not be able to use REF CURSOR types to specify
column types in statements to CREATE TABLEs or CREATE VIEWs.
• The elements in a nested table, index-by table, or variable array (VARRAY) cannot store the values of cursor variables.
You will not be able to use REF CURSOR types to specify the element type of a collection.
• Cursor variables cannot be used with dynamic SQL (through use of the DBMS_SQL package).