PL/SQL Ankita Kachwaha
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 2/191
Disadvantages of SQL
No pr ocedural capabilities.
SQL statements are passed to oracle engineone at a time.
No facility to handle err ors.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 3/191
Advantages of PL/SQL
Pr ovide facility of condition checking, looping,
and branching.
Entire block of statement is passed to oracleengine.
Permit dealing with err ors.
All so
rto
f calculatio
n can be do
ne quickly andefficiently.
PL/SQL blocks are portable.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 4/191
PL/SQL block
BEGIN
END;
EXCEPTION
DECLARE
END;
««
BEGIN
EXCEPTION
«
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 5/191
DECLARE (Optional)
Variables, cursors, user-defined exceptions
BEGIN (Mandatory)SQL statements
PL/SQL statements
EXCEPTION (Optional)
Actions to perf orm when err ors occur
END; (Mandatory)
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 6/191
Execution environment
PL/SQL
block
PL/SQL engine
Oracle server
Procedural
statement
executor
PL/SQL
SQL
SQL statement executor
PL/SQL
block
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 7/191
Character set
Uppercase / lower case alphabet.
Numbers
Symbols
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 8/191
Variable declaration
Var_name [constant] data type [not null]
[:=value];
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 9/191
Data type in pl /sql
Scalar type
Composite type
LOB type Reference type
Object type
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 10/191
Scalar type
Number (p, s)
Declaration value stored value
Number 1234.678 1234.678
number (3) 123 123
number (3) 1234 err or
number (4,3) 123.456 err or- exceed precision
number (4,3) 1.234567 1.235
number (7, 2) 12345.67 12345.67
number (4, -3) 1234 1000
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 11/191
Char
Varchar2
Date Long
Long raw/raw
Boolean (true, false, null)
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 15/191
OBJECT TYPE
% type
This declares a variable of the same type aspreviously defined variable or column of a
table or view.
Identifier Table.column_name%TYPE;
v_min_balance v.balance%TYPE := 10;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 16/191
Variable
Must begin with character and have
maximum length of 29.
Reser ve words can be used as variable butmust be enclosed in double quote.
Spaces and special symbol not allowed
except underscore.
Var_name data type(size) [default value];
Var_name data type(size)[ :=value];
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 17/191
Constraint
Constraint must be assigned values
immediately.
Pi const number (4,2):=3.14;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 18/191
Displaying messages
DBMS_ OUTPUT is a package.
PUT_LINE is a pr ocedure which accept onlysingle parameter of character type.
Set ser ver
output
on;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 19/191
Reading value of variable
Variable name:=& variable name;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 21/191
SQL> SET SERVEROUTPUT ONSQL>
SQL> BEGIN2 DBMS_OUTPUT.PUT_LINE(4 * 2);
3 DBMS_OUTPUT.PUT_LINE(24 / 3);4 DBMS_OUTPUT.PUT_LINE(4 + 4);5 DBMS_OUTPUT.PUT_LINE(16 - 8);
6 END;7 /
88
88
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 22/191
SQL> set ser ver output onSQL> declare
2 v _length NUMBER :=5.5;3 v _width NUMBER :=3.5;4 v _area NUMBER;5 begin
6 v _area:=v _length*v _width;7 DBMS_ OUTPUT.put_line(' Area:'||v _ar ea);8 end;
9 / Area:19.25
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 23/191
Assign SQL query results to
PL/SQL variables
SQL> declare2 v_name VARCHAR2(256);3 begin4 select first_name
5 into v_name6 from employee7 where id=7;8 DBMS_OUTPUT.put_line('v_name:'||v_name);9
10 end;11 /v_name:David
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 24/191
Scope Rules
Scope means the range of code within
which a given identifier can be referenced.
An identifier can be referenced only by codeexecuting inside the block in which the
identifier was declared.
An identifier could be a variable name, or a
pr ocedure name, function name.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 25/191
Demonstrate nested PL/SQL
blocks
SQL> declare2 v _custno NUMBER := 100;3 begin4 dbms_ output.put_line(v _custno) ;5 declare6 v _state CHAR(2):= 'NY' ;7 begin8 dbms_ output.put_line(v _custno || v _state) ;9 end ;
10 end ;11 /100100NY
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 26/191
dbms_utility.get_time
start number default dbms_utility.get_time;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 27/191
Conditional control
If <condition> then
<action>
elsif <condition> then<action>
else
<action>end if;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 28/191
Example
Declare
cur_bal number(10,2);
acno number(4);
Begin
select bal into cur_bal from acct whereacctno=141;
if cur_bal < 5000 then
update acct set bal=bal-100 where accno=141;end if;
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 29/191
Type of loops
Simple loop
While loop
For loop
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 30/191
Simple loop
Loop
<body of loop>
<end loop>
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 31/191
Example
Declare
i number:=0;
Begin
loop
i:= i+2;
exit when i>10;
end loop;dbms_ output.put_line(µloop end when i=µ||to _char (i));
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 32/191
While loop
While <condition>
loop
<action>end loop;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 33/191
example
Declare
pi constant number(4,2):=3.14;
radius number(5);
area number(14,2);begin
while radius <=7
Loop
A
rea:=pi*power(radius,2);Insert into areas values (radius, area);
radius:=radius+1;
end loop;
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 34/191
For loop
For variable in [reverse] start ..end
loop
<action>end loop;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 35/191
Example
Declare
no varchar2(5):=µ65432¶;
str_len number(4);
reverse varchar2(5);Begin
str_len:=length(no);
for count in reverse 1..str_len
loopreverse:=reverse||substr(no,count,1);
end loop;
dbms_output.put_line(µreverse no is µ||reverse);
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 37/191
Example
Declare
no number (5);
Beginno:=&no;
if no>5 then
goto mark;
end if;
dbms_ output.put_line(µmore than 5¶);
<<mark>>
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 38/191
Restriction on go to
Begin
goto inner block; -- illegal cannot branch to an inner block
begin
«..
<<inner block >>
«..
end;
goto innerif ; -- illegal cannot branch into an if statement
if 9>3 then
««.
<<innerif >>
««..
end if;
end;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 39/191
Begin
if 9>3 then
goto next; -- illegal to branch from one if clause to another
else
<<next>>;
«««
end if;
end;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 40/191
Illegal to branch from an exception
handler to current block
Declare
««...
begin
««..<<back>>
««..
exception
«««
goto back;
end;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 41/191
Labeling
Labeled statement
Labeled block
Labeled loops
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 42/191
Labeled statement
«««..
«««..
<<table_select>>select * fr om emp;
«««..
«««..
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 43/191
Labeled block
<<block1>>
declare
rno number (5);
beginrno:=&rno;
select * fr om std where rno=block1.rno;
<<block2>>
begin
««««
end;
end;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 44/191
<<o>>
declare
i number (2):=1;begin
dbms_ output.put_line(i);
<<ii>>
declare
i number (2):=10 ;
begin
dbms_ output.put_line(o.i);
dbms_ output.put_line(ii.i);
dbms_ output.put_line(i);
end;
end;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 45/191
Oracle tractions
Transaction is series of operation perf orm on
DB. Following events take place
connecting to oracle
committing changes to DB
r o
llbackdisconnecting fr om DB
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 46/191
transaction has four fundamental
properties, known as ACID properties:
Atomicity Transactions are committed or rolledback as a group, and are atomic, meaning that allSQL statements contained in a transaction areconsidered to be a single indivisible unit.
Consistency Transactions ensure that the databasestate remains consistent, meaning that thedatabase starts at one consistent state and ends inanother consistent state when the transactionfinishes.
Isolation Separate transactions should appear torun without interfering with each other.
Durability Once a transaction has been committed,the database changes are preserved.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 47/191
Commit
Ends the transaction and make the changes
permanent.
Commit;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 48/191
Rollback
Remove the changes made during a
transaction.
r ollback [to [savepoint] <save point name>]
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 49/191
Creating save point
Savepoint <save point name>;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 50/191
Rollback without Savepoint
clause
Ends the transaction.
Undoes all the changes.
Erase all save point in that transaction.
Release the transaction lock.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 51/191
Rollback with Savepoint
A predetermined portion of transaction is r oll
backed.
Release the transaction lock.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 52/191
Example
Declare
no number (5);
Begin
no:=&no;savepoint no _update;
update emp set sal=sal+no;if no>5000 then
r ollback to savepoint no _update;end if;
commit;
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 53/191
Flashbacks
If you mistakenly commit changes and you
want to view r ows as they originally were, you
can use a query flashback .
EXECUTE DBMS_ FLASHB ACK.EN ABLE_A
T_TIME(SYSDATE - 10 / 1440);
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 54/191
Record data type
Declare
type stdrec is record(
rno number (3),
namevarchar2(10),per number (4,2));
s1 stdrec;
begin
s1.rno:=10;
s1.name:=µxyz¶;
s1.per:=68;
end;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 55/191
Show file content
declarefid UTL_ FILE.FILE_TYPE := UTL_ FILE.FOPEN (loc, file, 'R');line VARCHAR2(2000);
BEGINDBMS_ OUTPUT.PUT_LINE (file);LOOPUTL_ FILE.GET_LINE (fid, line);DBMS_ OUTPUT.PUT_LINE (line);
exit when no _data_f
ound;END LOOP;
end;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 56/191
Writing on a file
declarefid UTL _FILE.FILE_TYPE : = UTL _FILE.FOPEN (loc, file, µw');v VARCHAR2(2000);BEGIN
v:=µvdvfdbfbd¶;
UTL _FILE.PUT _LINE (fid, v);UTL _FILE.FCLOSE (fid);
end;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 57/191
Cursor
The oracle engine uses a work area f or
internal pr ocessing in order to execute an sql
statement.
Active data set.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 58/191
Type of cursor
Implicit cursor.
Explicit cursor.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 59/191
Implicit and explicit cursor has
4 attribute
%ISOPEN
%FOUND
%NOT FOUND
%ROWCOUNT
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 60/191
IMPLICIT CURSOR.
Oracle engine open this cursor and manage
it.
The value of this cursor always refer to most
recently executed sql statement.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 61/191
Example
Begin
update acct set bal=bal+5000 where
acno
=141;if sql%notf ound then
dbms_ output.put_line(µerr or in updation¶);
end if;
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 62/191
For loop with implicit cursor
Begin
for cur1 in(select rno, name, per from std where per >=60)
loop
insert into std1 values(cur1.rno, cur1.name, cur1.per);end loop;
end;
/
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 63/191
Explicit cursor
� Create a
named
SQL area
DECLAREDECLARE
� Identify
the active
set
OPENOPEN
� Load the
current
row into
variables
FETCHFETCH
� Release
the active
set
CLOSECLOSE
Yes
� Test for
existing
rows
EMPTY?EMPTY?
� Return toFETCH if
rows are
found
No
1. Open the cursor.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 64/191
Cursor
pointer
p
2. Fetch a row using the cursor.
Cursor
pointer
Continue until empty.
Cursor
pointer
3. Close the cursor.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 65/191
Cursor declaration
A cursor is defined in declarative part of a
pl/sql block.
Cursor <cursor name> is select statement;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 67/191
Fetching record from cursor
Fetch <cursor name> into var1, var2,««;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 69/191
Explicit cursor attributes
%f ound
%notf ound
%isopen
%r owcount
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 70/191
Example
DECLARE
v_empno employees.employee_id%TYPE;
v_ename employees.last_name%TYPE;
CURSOR emp_cursor IS
SELECT employee_id, last_name
FROM employees;BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_empno, v_ename;
EXIT WHEN emp_cursor%ROWCOUNT > 10 OR
emp_cursor%NOTFOUND;
DBMS _OUTPUT.PUT _LINE (TO_CHAR(v_empno)
||' '|| v_ename);
END LOOP;
CLOSE emp_cursor;
END ;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 71/191
Cursor example
Declare
cursor c1 is
select name, sal from emp;
name emp.name%type;
sal emp.sal%type;Begin
open c1;
loop
fetch c1 into name, sal;
exit when c1%notfound;dbms_output.put_line(name||¶ µ||to_char(sal));
end loop;
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 72/191
%rowtype
Declare
cursor c78 is select rno, name, per from std1 where namelike µa%¶;
varcur c78 %rowtype;
begin
open c78;
fetch c78 into varcur;
while c78%found loop
dbms_output.put_line(varcur.rno ||¶ µ|| varcur.per);fetch c78 into varcur;
end loop;
end;
/
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 73/191
Illegal fetch
Cursor c1 is select * fr om std;
Fetch c1 into
b_rno, b_per; (err
or)
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 74/191
Cursor using for loop
For <variable> in <cursor name>
Here f or l
oop
variable is aut
omaticallycreated of %r owtype.
C f l t ti ll
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 75/191
Cursor for loop automatically
do the following
Implicitly declared its loop index as a
%r owtype record.
Open a cursor.
Fetch a r ow fr om cursor f or each loop
iteration.
Closes the cursor when all the r ows have
been pr ocessed.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 76/191
Example
Declare
cursor c2 is select eid, sal fr om emp wheredeptno=20;
Beginf or emp_rec in c2
loop
update emp set sal=emp_rec.sal+1000;
end loop;commit;
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 77/191
Parameterized cursor
Cursor <cur name> (var data type,«)
is <select statement>;
Open <cur name> (value/variable/expression;)
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 78/191
Example
Declare
cursor c_emp (No NUMBER) is select count(*) fromemployee where deptno = No;
deptNo
employee.deptn
o%type:=10;countEmp NUMBER;
Beginopen c_emp (deptNo);fetch c_emp into countEmp;
close c_emp;dbms_ output.put_line(to _char (countEmp));
End;
/
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 79/191
Cursor for updation
Cursor c1 is select name, per fr om std f or
update;
Any changes are not reflected to DB if update
clause is not specified.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 80/191
Fetching across commit
Commit must be used after all fetch
statement in case of update cursor. If used
inside loop than it will release all the locks
and any further fetch will fail.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 81/191
Reference cursor SQL> declare
2 c1 sys_refcursor;3 abc a%rowtype;
4 begin
5 open c1 for select no from a ;
6 loop
7 fetch c1 into abc;
8 exit when c1%notfound;
9 dbms_output.put_line(abc.no);
10 end loop;
11 close c1;
12 end;
13 /1
11
111
1111
PL/S L rocedure successfull com leted.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 82/191
Creating table variable
Type tab1 is table of std.per %type;
Type tab2 is table of std%r owtype;
Type tab3 is table of number index bybinary_integer;
Type tab4 is table of date index bybinary_integer;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 83/191
ExampleDeclare
type notab is table of number index by binary_integer;
v1 notab;
Begin
f or v2 in 1..10 loop
v1(v2):=v2*10;
end loop;
Dbms_ output.put_line(µtable elements are);
f o
r v
2 in 1..10 loo
pDbms_ output.put_line(v1(v2));
end loop;
End;
/
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 84/191
Varray
Type <var> is varray (size) of type [not null];
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 85/191
Example
DeclareType no is varray (20) of number (3);
V1 no;
V2 no:= no(11,22);
V3 no:=no (null);
Begin
if v3 is null and v1 is null then
dbms_ output.put_line(µnull¶);
End if;
V2(1):=& V2(1);V2(2):=& V2(2);
End;
/
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 86/191
Pl /sql security
For concurrency contr ol locking method is
used.
Implicit locking
Explicit locking
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 87/191
Type of locks
Shared lock
Exclusive l
ock
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 88/191
Level of lock
Row level
Page level
Table level
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 89/191
Explicit locking
Client a> select * fr om std where rno=10 f or
update;
Record will be locked and released when
commit or r ollback is fired.
Client b> select * fr om std where rno=10 f or
update;
Client a> select * fr om std where rno=10 f or update nowait;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 90/191
Lock table
Lock table <tn1> [,<tn2>,«.]
in {r ow share | r ow exclusive | share update |
share | share r ow exclusive | exclusive }
[nowait]
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 91/191
Releasing lock
Commit
Rollback
Rollback to save point
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 92/191
Deadlock
Transaction 1
begin
update std set per=90 where rno=10;
update std set per=50 where rno=20;end;
Transaction 2
begin
update std set per=50 where rno=20;update std set per=90 where rno=10;
end;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 93/191
Exception handling
Exception condition
Exception handler
Named exception(15-20)
Numbered exception(20000)
Default exception handling
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 94/191
Error type
Err or type reported by handled by
Compile time pl/sql compiler compiler report
err or
Runtime pl/sql runtime exception
engine handler
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 95/191
Syntax
Exception
when <exception name> then
<user specified action>
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 96/191
Named exception
DUP _VAL_ ON _ INDEX
LOGIN _DENINED
NO _DATA_ FO
UND
PROGRAM _ERROR
TIMEOUT_ ON _RESOURCE
TOO _ M ANY _ROWS
VALUE_ERROR
OTHERS
TIMEOUT ON RESOURCE
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 97/191
TIMEOUT_ ON _RESOURCE
TRANSACTION _ B ACKED_ OUT
INVALID_CURSOR ZERO _DIVIDE
INVALID_ NUMBER (eg char to number)
STORAGE_ERROR
VALUE_ERROR (eg conversion, truncation err or)
ROWTYPE_ MISM ATCH
CURSOR_ALREADY _ OPEN
COLLECTION _ IS_ NULL SUBSCRIPT_ OUTSIDE_LIMIT
SUBSCRIPT_ BEYOND_COUNT
CASE_ NOT_ FOUND
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 98/191
EXAMPLE
Declarev1 std.per % type;
Begin
select per into v1 fr
om std where rn
o=10;
dbms_ output.put_line(v1);
Exception
when no _data_f
ound then
dbms_ output.put_line(µno record f ound¶);
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 99/191
User named exception handlers
Declare
<exception name> exception;
pragma exception_init(<exception name>,<error no>);
Begin
.
.
.
Exception
when <exception name> then.
.
.
End
E l
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 100/191
Example
Declarev1 std.per % type;
v2 std.rno %type;
resource_bsy exception;
pragma exception_init(resourse_bsy,-00054);
Begin
update std set per=&v1 where rno=&v2;
Exceptio
nwhen resource_bsy then
dbms_ output.put_line(µr ow is used by other¶);
End;
User defined exception handling
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 101/191
p g
for business rule validations
Declare<exception name> exception;
Begin
.
.if <condition> then
raise <exception name>;
end if;
Exception
when<exception name> then
<action>
End;
Example
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 102/191
ExampleDeclare
r std.rno %type;
n std.name % type;
p std. per %type;
temp number (2);
e1 exception;
Begin
r:=&r;
n:=&n; p:=&p;
Select count(rno) into temp from std where rno =r;
If temp = 0 then
insert into std values(r,n,p);
else
raise e1;
end if;
Exception
when e1 then
dbms _ output. put _ line(µerror in insertion¶);
End;
Control passing to exception
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 103/191
Control passing to exception
handler
Declare
e1 exception;
Begin
««raise e1;
««
Exception
when e1 then«««
End;
SQL> BEGIN
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 104/191
DBMS_ OUTPUT.PUT_LINE(1 / 0);EXCEPTION
WHEN OTHERS THENDBMS_ OUTPUT.PUT_LINE(' An exception occu
rred');WHEN ZERO _DIVIDE THEN
DBMS_ OUTPUT.PUT_LINE('Division by zer o');
END;/WHEN OTHERS THEN
*ERROR at line 4:ORA-06550: line 4, column 4:PLS-00370: OTHERS handler must be last among the exception handlers of a block
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 105/191
Sqlcode and sqlerrm
Inside others handler it is often useful to
know which oracle err or raise exception.
Sqlcode returns current err or code.
Sqlerrm return err or message text.
Example
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 106/191
Example
Declarev1 std.rno % type;
Begin
select rno into v1 fr om std;
Exception
when others then
dbms_ output.put_line (sqlcode || sqlerrm);
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 107/191
Raise application error
Raise_application_err or (no, msg );
No
can be between -20000 and -20999
Msg can be 512 characters
Example
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 108/191
ExampleDeclare
temp number (5);
Begin
select count (rno) into temp fr om std;
if temp <1 then
raise_application_err or (-20001,¶no student
data available¶);
end if;End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 109/191
Error propagation
If current block has a handler f or exception
than execute it and complete the block
successfully. Later on contr ol is passed to
enclosing block.
If there is no handler f or the exception than
pr opagate it to the enclosing block which will
handler it if handler is define f or thatexception otherwise default exception
handler will handle the exception.
Declare
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 110/191
Declare
a exception;
Begin
Begin
raise a;
Exception
when a then
«««.
End;
End;
Exception a is
raised in subblock
Exception a is
handled in sub
block
Declare
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 111/191
a exception;
b exception;
Begin
Begin
raise b;
Exception
when a then
«««.
End;
Exception
when b then
«««
End;
Exception b is
raised in subblock
No handler for
b in sub block
Exception b ispropagated to
outer block and
handled there
Declare
a exception;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 112/191
b exception;
c exception;
Begin
Begin
raise c;
Exception
when a then
«««.
End;
Exception
when b then
«««
End;
Exception c is
raised in subblock
No handler for
c in sub block
Exception c is
propagated to
outer block butthere is no
handler
Exception will be
handled by
default handler
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 113/191
Declare
num number(3):=µabc¶;
Begin
.
.
.
.
Exception
when others then
.
.
End;
Value
error
Even others handler
exist it is not executed
Block¶s value error
exception will be
handled by default
handler
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 114/191
Begin
Declare
num number(3):=µabc¶;
Begin
«««
Exception
when others then
««..
End;
Exception
when others then
.
.
End;
Value
error
Even others handler
exist in inner block it isnot executed
Outer block
exception handler
will handle it
Declare
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 115/191
a exception;
b exception;
Begin
raise a;
Exception
when a then
raise b;
when b then
«..
End;
Exception
a is raised
Exception b is
raised
Even thoughthere is a handler
for b here, it is
not executed. The
exception is
propagated out of
block
Block completes
unsuccessfully
with unhandled
exception b
Begin
Exception a is
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 116/191
Declare
a exception;
b exception;
Begin
raise a;
Exception
when a then
raise b;
when b then
«««..
End;
Exception
when b then
«««
End;
Exception a is
raised
Exception is
handled and b is
raised
Even though handler
for b exist still it willpropagate out of block
Exception b is
handled here
Exception
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 117/191
Declare
a exception;
Begin
raise a;
Exception
when a then
««««.
raise;
End;
Exception
a is raised
Exception a is
handled
Same exception is
raised again
Exception is
propagated out of the
block
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 118/191
Procedure and functions
These are set of sql and pl/sql statement that
perf orm specific task.
Consist of 3 parts
declarative part
executable part
optional exception handling part
Where procedure and function
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 119/191
are saved
Stored in oracle database
Invoked by any pl/sql block
Bef ore saving pr ocedure or function oracle
engine parses and compiles it.
If err or occur during compilation invalid
pr ocedure or function is created.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 121/191
Steps of execution
Verify user access
Verify pr ocedure or function validity
Executes pr ocedure or function
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 122/191
Advantages
Security
Perf ormance
Memory allocation
Pr oductivity
Integrity
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 123/191
Procedure vs. functions
Function can return a value back to calling point. A
function can return only one value to calling point.
By defining multiple out parameter in pr oceduremultiple values can be passed to calling point.
A pr ocedure call is a pl/sql statement while function
call is a part of an expression.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 124/191
Syntax of procedure
Create or replace procedure [schema.]<name>
(<argument>{in,out,in out}<data type>,«){is,as}
<variable constant declaration>;
Begin
««..
Exception
«««
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 125/191
Syntax of function
Create or replace function [schema.]<name>
(<argument>in<data type>,«)
R eturn <data type> {is,as}
<variable constant declaration>;
Begin
««..
Exception
«««
End;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 126/191
Return statement
There can be more than one return statement
in a function although only one of them will be
executed.
It will be an err or if there is no return
statement in a function.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 127/191
Example
Create or replace function f1 (sal1 in number)
Return number is
Temp number (5);
Begin
select count (eid) into temp fr om emp where
sal > sal1;
return temp;
End;
Declare
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 128/191
v1 number (3);
Beginv1:=&v1;
v1:=f1(v1);
dbms_ output.put_line(v1);End;
Example procedure
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 129/191
Example procedure
Create or replace pr ocedure p1(rnoo innumber, namee in varchar2, perr number) is
Begin
insert into
stdvalues(rn
oo, namee, perr);
End;
Declare
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 130/191
namee std.name %type:=µabc¶;
rnoo std.rno %type:=10;perr std.per %type:=70;
Begin
p1(rnoo, namee, perr);End;
Deleting stored procedure or
f ti
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 131/191
function
Dr op pr ocedure <name>;
Dr op function <name>;
P t f d
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 132/191
Parameter of procedure
Name [mode] data_type:=default value;
M d
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 133/191
Mode
In
Out
In out
Passing parameter by value and by reference
I
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 134/191
In
The value of actual parameter is passed into
pr ocedure when pr ocedure is invoked. Inside
pr ocedure f ormal parameter act like pl/sql
constraint and cant be changed.
O t
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 135/191
Out
Any value actual parameter has when
pr ocedure is called is ignored. Inside the
pr ocedure f ormal parameter act like
un-initialized pl/sql variable and has nullvalue. When pr ocedure finishes and contr ol
return to calling envir onment content of
f ormal parameter are assigned to actual
parameter.
I t
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 136/191
In out
This is combination of in out. The value of
actual parameter is passed into pr ocedure
when pr ocedure is invoked. Inside pr ocedure
f ormal parameter act like an initializedvariable and can be read and written. When
the pr ocedure finishes contr ol return to calling
envir onment and content of f ormal parameter
are assigned to actual parameter.
E l
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 137/191
Example
create or replace pr ocedure p1
( v1 in number, v2 out number, v3 in out number) is
lv1 number:=0;
beginlv1:=v1; /* v1:=4 ; err or */
v2:=4; /* lv1:=v2; err or */
v3:=v3+v3;
end;
SQL> declare
2 v11 number:=11;
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 138/191
2 v11 number:=11;
3 v22 number:=22;
4 v33 number:=33;
5 begin
6 p1(v11,v22,v33);
7 dbms_ output.put_line(v11||¶ µ ||v22||¶ µ||v33);8 end;
9 /
11 4 66
PL/SQL pr ocedure successfully completed.
% t pe proced re parameter
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 139/191
% type procedure parameter
Create or replace pr ocedure p1
(vrno std.rno%type,«««)is
Exception inside subprogram
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 140/191
Exception inside subprogram
If pr ocedure or function has no exception
handler f or the exception condition than
contr ol immediately passes out to the calling
pr ogram i.e. calling envir onment inaccordance with exception pr opagation rule.
Package
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 141/191
Package
Package is oracle object which hold other objects within it.
Allow efficient organization of commercial
application Allow granting of privileges efficiently
Enable overloading of function and pr ocedure
Impr oves perf ormance by loading multipleobjects into memory.
Pr omote reuse of code.
Package specification
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 142/191
Package specification
Name of the package
Name of the variable and data type
This declaration is local to the DB and local to
the package.
Package declaration
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 143/191
Package declaration
Create package pack1 is
function f1(v1 in varchar2) return number;
pr ocedure p1(v2 in varchar2, v3 in varchar2);
End pack1;
Package body
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 144/191
Package body
Create or replace package body pack1 as
function f1(v1 in varchar2) return number
begin
«««
exception«««
end;
pr ocedure p1(v2 in varchar2, v3 in varchar2)
begin
«««exception
«««..
end;
End pack1;
Invoking a package
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 145/191
Invoking a package
Verify user access.
Checks that pr ocedure is valid or not if not
than it is automatically recompiled.
The package subpr ogram is executed.
Syntax for using package
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 146/191
Syntax for using package
Package_name.type_name
Package_name.object_name
Package_name.subpr ogram_name
Executing package members
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 147/191
Executing package members
Execute pack1.p1(µgsfhd¶);
Execute pack1.p1(v22);
Call pack1.p1(v22);
Package object: private /
public
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 148/191
public
Any item declared within package
specification are public i.e. visible outside the
package.
All items declared inside package body are
private.
Overloading procedure and
functions
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 149/191
functions
Functions with same name but different
parameters are called overloaded function.
Create or replace package check isfunction ok (date1 in date) return number;
function ok (num in number) return number;
end check;
Create or replace package body check is
function ok (date1 in date) return number
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 150/191
begin
if date1< sysdate thenreturn 1;
else
return 0;
end if;
end;function ok (num in number) return number
begin
if num<10 then
return 0;
else
return 1;
end if;
end;
End check;
Calling
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 151/191
Calling
Begin
if check .ok (22) = 1 then
dbms _ output. put _ line(µnumber is greater than 10¶);
end if;
End;
Restriction
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 152/191
Restriction
At least one of the parameter of overloading
function or pr ocedure must differ.
Overloading pr ocedure or function cant have
same number of parameters with different
name and different mode but same data type.
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 153/191
Overloading functions or pr ocedures withsame parameter name , mode and data type
but different return type are not permitted.
All the overloaded modules must be defined
within same scope or block.
Trigger
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 154/191
Trigger
Trigger are the implicit pr ocedure that are
implicitly executed when insert, update,
delete is issued against a table.
Use of trigger
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 155/191
Use of trigger
A trigger can permit DML statement against a
table only if they are issued during regular
business hours.
It can be used to prevent invalid transaction.
Enf orces complex security.
It can also be used to keep track of updated
or deleted records.
Cascading trigger
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 156/191
Cascading trigger
When a trigger is fired sql statement inside
trigger can also fire some other trigger. This
is called cascading trigger.
Trigger vs procedure
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 157/191
Trigger vs. procedure
Trigger do not accept parameter whereas
pr ocedure can.
Trigger is executed implicitly by oracle engine
itself upon modification of an associated
table. To execute pr ocedure it has to be
explicitly called by user.
Trigger vs integrity constraint
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 158/191
Trigger vs. integrity constraint
Integrity constraint is a statement about DB
that is always true.
Trigger contain what a transaction can do i.e.
trigger do not apply to data loaded so it don't
guarantees that all the data in the table
confirms rules.
How to apply database
triggers
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 159/191
triggers
Triggering event or statement
Trigger restriction
Trigger action.
Type of trigger
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 160/191
Type of trigger
Row triggers
fired each time a r ow in the table is affected.
E.g. update statement changes multiple r owsthan trigger is fired f or each r ow.
Statement trigger
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 161/191
Statement trigger
Fired once on behalf of triggering statement.
Independent of number of r ows affected.
Used when pr ocessing is required which is
independent of number of r ows affected.
Before triggers
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 162/191
Before triggers
Trigger action are executed bef ore triggering
statement.
Bef ore trigger determine whether or not
triggering statement should be allowed to
complete.
After trigger
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 163/191
After trigger
Trigger action are executed after triggering
statement.
Combinations
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 164/191
Combinations
Bef ore statement trigger
Bef ore r ow trigger
After statement trigger
After r ow trigger
Syntax
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 165/191
Syntax
Create or replace trigger <name>
{before, after}
{delete, insert, update [of column«.,..]}
On <table name>
[referencing {OLD as old, NEW as new }]
[for each row [when condition]]
Declare
««
Begin««..
Exception
«««
End
Create trigger audit
after update or delete on cust
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 166/191
f or each r ow
DeclareOp varchar (20);
Begin
if updating then
op:=µupdate¶
Elsif deleting then
op:=µdelete¶;
End if;
Insert into cust_backup values(:old.cust_id, :old.name,:old.sal, user, sysdate);
End;
Three categories
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 167/191
ee catego es
DML trigger
Instead-of trigger
System trigger
DML trigger
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 168/191
gg
This trigger is fired by a DML statement.
DML trigger can be defined f or insert, update
or delete operation.
Instead-of trigger
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 169/191
gg
These triggers can be defined only on views.
Instead of trigger will be executed instead of
DML statement.
Instead of trigger must be r ow level.
Example
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 170/191
p
Create or replace view class as
select dept, building, r oomno fr om classes
where building=µbcom¶;
Insert into class values(µsci¶, µbe¶, 10);
Create or replace trigger classtrigger
Instead of insert on class
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 171/191
DeclareTemp number (3);
Begin
select count (r oomno) into temp fr om classes
where r oomno=10 and building=µbe¶;if temp=0 then
Insert into classes values(µsci¶, µbe¶, 10);
else
dbms_ output.put_line(µ insert not possible¶);
end if;
End;
System trigger
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 172/191
y gg
System trigger fires when a system event
such as DB startup or shut down occurs.
System trigger can also be fired on DDLstatement
Create or replace trigger logcreate
After create on schema
8/4/2019 PLnew
http://slidepdf.com/reader/full/plnew 173/191
After create on schema
Begininsert into db_tab (user_id, object_type,
object_name, object_ owner,
createion_date) values(user, sys.dictionary_ obj_type,
sys.dictionary_ obj_name,
sys_dictionary_ obj_ owner, sysdate);End;