Professional Documents
Culture Documents
com
Introduction
Advantage of sub-block:
Global and local variables can be declared
Data hiding as encapsulation
Efficient error handling (exception)
Instructions:
Create an output table and put all programs output in Output Table
As the result can’t be shown into the screen send it to Output Table
Table Output: Create table output (File number (4), sec char (15));
Program No 1. p1.sql
SQL>Ed p1.sql
Begin
Insert into output values (1,’iflex’);
End;
/
SQL> @p1
-- compiles and execute
-1-
PL/SQL Procedure successfully completed
SQL>select * from output;
Program No 2. p2.sql
SQL>Ed p2.sql
Declare
X number(4);
-- store a null value take 1 bytes in RAM no garbage collection in PL/SQL
Begin
X:= 100; -- := assignment operator
Insert into output values (x,’iflex’);
End;
/
Program No 3. p3.sql
SQL>Ed p3.sql
Declare
X number(4) := 100;
-- declare and assign value at same time [recommended]
Begin
Insert into output values (x,’iflex’);
End;
/
Program No 4. p4.sql
SQL>Ed p3.sql
Declare
X number(4);
Begin
X:= &x; -- possible because common compiler for SQL SQL*Plus PL/SQL
Insert into output values (x,’iflex’);
End;
/
SQL>@p4
Enter value of x: 100
-2-
Program No 6. p6.sql
SQL>Ed p6.sql
Clea scre
Accept x number prompt “Please enter the Name”
Declare
X char(15);
Begin
X:= &x;|X:= ‘&x’; |X:= &x;
Insert into output values (1,x);
End;
/
Undefine x
Select * from output;
Delete output;
@p6
Please enter the Name: ’KING’|KING|1234
-- 1234 possible as implicit data type conversion is in Oracle only for number to char
Program No 7. p7.sql
SQL>Ed p7.sql
Declare
X constant number(4) := 1000;
-- constant must be define at declare section otherwise it be an error
Begin
Insert into output values (x,’iflex’);
End;
/
Program No 8. p8.sql
SQL>Ed p8.sql
Declare
X char(15);
Y number(7);
Z number(7);
Begin
X:= ‘&ename’;
Y:= &salary;
Z:= y*0.4;
End;
/
-3-
Program No 9. p9.sql
SQL>Ed p9.sql
Set verify off
Set serveroutput on
-- serveroutput on[off] SQL*plus command
Declare
X char(15);
Y number(7,2);
Z number(6,2);
Begin
X:= '&ename';
Y:= &salary;
Z:= Y*0.4;
DBMS_OUTPUT.PUT_LINE('HELLO');
DBMS_OUTPUT.PUT_LINE('ENAME = '||X);
DBMS_OUTPUT.PUT_LINE('SALARY ='||Y);
DBMS_OUTPUT.PUT_LINE('HRA ='||Z);
-4-
Program No 12. p12.sql
SQL>Ed p12.sql
Declare
Z emp.sal%type;
Y emp.job%type;
-- Exact match if column precession changes then it helps
Begin
Select sal, job into Z,Y from emp where ename = ‘KING’;
Insert into output values (Z,Y);
End;
/
Begin
Select * from Z where ename = ‘KING’;
Insert into output values (Z.sal,Z.job);
End;
/
-5-
Program No 16. p16.sql
SQL>Ed p16.sql
Declare
Type abc is record
( A emp.sal%type;
B emp.job%type; );
Type pqr is record
( L number(4);
M abc; );
X pqr;
-- Structure within structure/ nested-structure
Begin
Select sal, job into X.M from emp where ename = ‘KING’;
-- Select deptno, sal, job into X from emp where ename = ‘KING’;
Insert into output values (X.M.A,X.M.B);
End;
/
-6-
If x>4000 then
Insert into output values (X, ‘High sal’);
Elsif x<4000 then
Insert into output values (X, ‘Low sal’);
Else
Insert into output values (X, ‘Med sal’);
End if;
-- elsif statement Else if is Nested if..
End;
/
If …………. Then
………………….
Elsif …………… Then
…………………
Elsif …………. Then
………………….
Else
If …………. Then
………………….
Else
…………………
End if;
End if;
-7-
Use Loops - For repetitive processing
Begin
-- While loop no increment/decrement operator
While X<10
Loop
While Y<10
Loop
Insert into output values (Y, ‘in Y loop’);
Y:=Y+1;
End loop;
Insert into output values (X, ‘in X loop’);
X:=X+1;
End loop;
End;
/
X=1
Y =1…9
X = 2….9
-8-
Loop
While Y<X
Loop
Insert into output values (Y, ‘in Y loop’);
Y:=Y+1;
End loop;
Insert into output values (X, ‘in X loop’);
X:=X+1;
End loop;
End;
/
X = 1 Y =1
X = 2 Y =2
……………..
X = 8 Y =8
X=9
X = 1...6
-9-
Program No 27. p27.sql
SQL>Ed p27.sql
Declare
X number(4):= 1;
Begin
While X<10
Loop
Insert into output values (X, ‘in X loop’);
Exit when x>5;
-- Exit when condition
X:=X+1;
End loop;
End;
/
X = 1...6
X:=X+1;
End loop;
End;
/
- 10 -
X = 1..10
- 11 -
Insert into output values (X, ‘X for loop’);
End loop;
End;
/
- 12 -
Rules for Goto:-
Can’t use goto to enter loop use only to come out of loop
Can’t use goto to enter IF construct use only to come out of IF construct
End, End If, End loop are non executable stmt so there must some executable stmt
between GOTO control and end; end loop; or end if;
Goto abc;
<<abc>>
End; /End loop; End if; -- not allowed
Solution: use null statement or dummy variable initialization x:= x;
Goto abc;
Null;
<<abc>>
End; /End loop; End if; -- allowed
Using GOTO from sub-block to super-block is allowed, but super-block to sub-block is not
allowed
Sub-blocks:
Main/super block can’t access sub-block variable
Sub-block can access super-block variable and modify its value
Two sub block within one super block always be independent
Program No 37. p37.sql
SQL>Ed p37.sql
Declare
X number (4):= 100;
Begin
Insert into output values (X, ‘before sub’);
Declare
Y number (4):= 200;
Begin
X; =X+Y;
Insert into output values (Y, ‘in sub’);
Insert into output values (X, ‘in sub’);
End;
Insert into output values (X, ‘after sub’);
-- Insert into output values (Y, ‘in sub’); not allowed
End;
/
- 13 -
Program No 39. p39.sql
SQL>Ed p39.sql
<<abc>> -- create a label
Declare
X number (4):= 100;
Begin
Insert into output values (X, ‘before sub’); -- global variable X
Declare
X number(4):= 200;
Begin
Insert into output values (abc.X, ‘in sub’); -- global variable X
End;
End;
/
<<abc>>
Declare 1
………x….;
Begin
………….;
Declare 2
………x….; call abc.x will call 1st block’s x
Begin
………….;
Declare 3
………x….; call abc.x will call 2nd block’s x
Begin
………….;
End;
End;
End;
<<abc>>
Declare 1
………x….;
Begin
………….;
<<pqr>>
Declare 2
………x….; call abc.x will call 1st block’s x
Begin
………….;
Declare 3
………x….; call abc.x will call 1st block’s x
Begin
………….;
End;
End;
- 14 -
End;
Declare 1
………x….;
Begin
………….;
<<abc>>
Declare 2
………x….; can’t call 3rd block’s pqr.x even with labels declared
Begin
………….;
End;
<<pqr>>
Declare 3
………x….; can’t call 2nd block’s abc.x with labels declared
Begin
………….;
End;
End;
http://in.briefcase.yahoo.com/emailtorakesh
--------------------------------------------------------------------------------------------------------------------
- 15 -
Cursors
Cursor in all RDBMS (like Record set)
Read only variable –data present in cursor can’t manipulated
Can’t Add/Update/Delete in Cursor
Similar 2D array
Used for storing/handling/processing multiple rows
Used for storing data temporarily (in RAM)
Based on a select statement
Open Single/one way linked list
Program No 40. p40.sql
SQL>Ed p40.sql
Declare
Cursor c1 is select * from EMP order by sal; -- Cursor declaration / definition [contains no data]
x emp%rowtype; -- only column wise 1 byte full of null value
Begin
Open c1; -- execute select statement and set cursor pointer points to first row/record
For y in 1..5
Fetch c1 to x; -- send 1st row’s data to x [actually return Boolean Value]
-- fetch data from cursor to intermediate variable
-- Cursor fetches data top to bottom / sequentially
-- [DB2 allows going cursor pointer backwards]
-- fetch only 1 row at a time
-- [multi row allowed in Informix sub-cursor concept]
Insert into output values (x.empno, x.ename); -- send data x to output table
End loop; -- 5 times in loop every time x is overwritten
Close c1; -- As cursor is a variable it automatically destroyed
-- CLOSE command to free up RAM
-- Closing the cursor is optional if it’s in last line of program
-- If want to OPEN cursor again for another purpose first close it then re-open it
-- Otherwise returns Error as cursor already opened
-- Cursor is open then Base table updated in cursor no modification done
End;
/
Program No 41. p41.sql “emp table only has 5 rows”
SQL>Ed p41.sql
Declare
Cursor c1 is select * from EMP order by sal;
x emp%rowtype;
Begin
Open c1;
For y in 1..10
Fetch c1 to x;
Insert into output values (x.empno, x.ename);
End loop; -- from 6th loop record of 5th row in EMP table inserted last 5 times.
Close c1;
End;
/
- 16 -
Program No 42. p42.sql -- not a recommended solution. Use Cursor Attributes/Functions:
SQL>Ed p42.sql
Declare
Cursor c1 is select * from EMP order by sal;
x emp%rowtype;
z number(4);
Begin
Select count (*) into z from emp;
Open c1;
For y in 1..z
Fetch c1 to x;
Insert into output values (x.empno, x.ename);
End loop;
Close c1;
End;
/
Cursor Attributes/Functions:
Program No 43. p43.sql
SQL>Ed p43.sql
Declare
Cursor c1 is select * from EMP order by sal;
x emp%rowtype;
Begin
Open c1;
Loop
Fetch c1 to x;
If c1%notfound then -- return a Boolean true value if last fetch is unsuccessful
-- cursor_name%notfound Works based on row id
Exit; -- exit when c1%notfound; (without using if construct)
Insert into output values (x.empno, x.ename);
End if;
End loop;
Close c1;
End;
/
Program No 44. p44.sql
SQL>Ed p44.sql
Declare
Cursor c1 is select * from EMP order by sal;
x emp%rowtype;
Begin
Open c1;
Loop
Fetch c1 to x;
If c1%found then -- return a Boolean true value if last fetch is 4successful
Insert into output values (x.empno, x.ename);
Else
Exit;
End if;
End loop;
Close c1;
End;
- 17 -
/
Program No 45. p45.sql
SQL>Ed p45.sql
Declare
Cursor c1 is select * from EMP order by sal;
x emp%rowtype;
y number(4);
Begin
Open c1;
Loop
Fetch c1 to x;
Exit when c1%notfound;
y: = c1%rowcount; -- how many rows fetched from the cursor so far
Insert into output values (y, x.ename);
End loop;
Close c1;
End;
/
- 18 -
Program No 48. p48.sql Integration of Cursor with loop *only in Oracle PL/SQL
SQL>Ed p48.sql
Declare
Cursor c1 is select ename,sal from EMP;
Begin
For x in c1 -- itself does the Open, fetch, Exit when c1%notfound and Close cursor.
Loop
Insert into output values (x.sal, x.ename);
End loop;
End;
/
Parameter to a Cursor
Program No 50. p50.sql
SQL>Ed p50.sql
Declare
Cursor c1 (dd number) is select * from EMP where deptno = dd;
Begin
For x in c1 (1) -- c1 (&d1) also taken from runtime
Loop
Insert into output values (x.sal, x.ename);
End loop;
For x in c1 (2)
loop
Insert into output values (x.sal, x.ename);
End loop;
End;
/
- 19 -
/
Program No 52. p52.sql
SQL>Ed p52.sql
Declare
Cursor c1 (dd number default 1) is select * from EMP where deptno = dd ;
Begin
For x in c1 -- specify default value for parameter
Loop
Insert into output values (x.sal, x.ename);
End loop;
End;
/
pfile Init.ora total parameter is 314 in Oracle 10g
OPEN_CURSOR = 300 – to manage cursor opened per session
Begin
For x in c1
Loop
For y in c2
Loop
If x.deptno = y.deptno then
Insert into output values (y.empno,x.dname);
End if;
End loop;
End loop;
End;
/
Program No 54. p54.sql --faster way [join works on this logic internally]
SQL>Ed p54.sql
Declare
Cursor c1 is select * from EMP;
Cursor c2 (dd number) is select * from DEPT where deptno = dd;
Begin
For x in c1
Loop
For y in c2 (x.deptno)
Loop
Insert into output values (y.empno,x.dname);
End loop;
End loop;
End;
/
- 20 -
Program No 55. p55.sql --fastest way [use joins] recommended
SQL>Ed p55.sql
Declare
Cursor c1 is select empno,deptno from EMP,dept where dept.deptno = emp.deptno;
Begin
For x in c1
Loop
Insert into output values (x.empno,x.dname);
End loop;
End;
/
- 21 -
/
- 22 -
(Whether successful or not), Can get a count of how many rows are effected during last DML
operation, maintain logs (audit trails) of DML operation, name of the implicit cursor accessible by
user is SQL.
Program No 60. p60.sql
SQL>Ed p60.sql
Declare
X number(4);
Begin
Update EMP set sal = sal+1 where deptno = 2;
-- Delete EMP where deptno = 2;
-- insert into SEMP select * from EMP;
If SQL%found then -- implicit cursor SQL
X:= SQL%rowcount;
Insert into output values (x, ‘updated’);
End if;
End;
/
- 23 -
Rony_CURSOR ex1
DECLARE
V_RAD NUMBER(5,2);
V_AREA NUMBER(5,2);
CURSOR mycur IS SELECT radius from RAD WHERE radius > 3 AND radius <7;
BEGIN
OPEN mycur;
LOOP
FETCH mycur INTO V_RAD;
EXIT WHEN mycur%notfound;
V_AREA := 3.14 * (V_RAD**2);
INSERT INTO CIRCLE VALUES(V_RAD,V_AREA);
END LOOP;
CLOSE mycur;
END;
/
Rony_CURSOR ex2
DECLARE
V_EMPNO NUMBER(4);
V_DATE DATE;
V_SAL NUMBER(7,2);
CURSOR EMP_AMT IS SELECT EMPNO,SAL FROM EMP WHERE DEPTNO =20;
BEGIN
OPEN EMP_AMT;
LOOP
FETCH EMP_AMT INTO V_EMPNO,V_SAL;
EXIT WHEN EMP_AMT%NOTFOUND;
V_SAL := V_SAL * 0.06;
V_DATE := SYSDATE;
INSERT INTO EMP_RAISE VALUES(V_EMPNO,V_DATE,V_SAL);
END LOOP;
CLOSE EMP_AMT;
END;
/
Rony_CURSOR ex3
DECLARE
V_EMPNO NUMBER(4);
V_TEMP NUMBER(2);
CURSOR EMP_CHK IS SELECT EMPNO FROM EMP2;
BEGIN
OPEN EMP_CHK;
V_TEMP := 0;
LOOP
FETCH EMP_CHK INTO V_EMPNO;
EXIT WHEN EMP_CHK%NOTFOUND;
V_TEMP := V_TEMP + 1;
END LOOP;
IF V_TEMP = 0 THEN
DBMS_OUTPUT.PUT_LINE('TRUE');
ELSE
DBMS_OUTPUT.PUT_LINE('FALSE');
END IF;
CLOSE EMP_CHK;
END;
/
- 24 -
Exceptions - error Handlers:
Al exceptions group together at end of block
Within the exception (error handling routine) all PL/SQL statements allowed
Can’t transfer control to from the exception to the block [compilation error]
Manage runtime error not Compile time error
Pre defined exception total 21 exceptions available (frequently encountered errors)
Error managed only between Begin and End Section not between Declare and Begin
section.
Error managed only between Declare and Begin section by encapsulating the section
into Parent block
1. too_many_rows
2. no_data_found
3. value_error -- for variable/value/data
4. invalid_number -- for column type
5. zero_divide
6. others -- default Exception
- 25 -
Exception when value_error then -- if value exceed the scale
-- X number (6, 2) X:= 100.786 Oracle automatically round off to 100.79 no error for precision
DBMS_OUTPUT.PUT_LINE (‘Value is to High’);
End;
/
Program No 63. p63.sql
SQL>Ed p63.sql
Declare
X number (4);
Begin
X: = Pune; -- assume Pune as variable
-- for variable not found no exception available in Oracle
End;
/
- 26 -
Declare
……………
X VARCHAR2 (10); Y VARCHAR2 (512);
Begin
……………
Exception When too_many_rows then
……………….
Exception When no_data_found then
………………..
Exception When value_error or invalid_number then
…………………
Exception When zero_divide then
……………….
Exception When others then
………………..
X:= SQLCODE; --SQL ERROR CODE for all types of error in Oracle
Y:= SQLERRM; --SQL ERROR MESSAGE for all types of error in Oracle
Insert into output values (X,Y,SYSDATE)
……………….
End;
/
-- To catch the line no. error as in multiple select stmt. Use a dummy variable & catch the error
using it.
Declare
X number (4);
Begin
x:= 1;
Select …………..;
x:= 2;
Select …………..;
Exception When too_many_rows then
If x=1 then
…………..;
Elsif x=2 then
……………;
Else
…………..;
End if;
End;
/
Declare
…………..
Begin
Declare
X number (4):= 10000;
Begin
Exception When value_error then
Insert into output values (1, ‘in sub error’); -- exception not encountered
- 27 -
End;
Exception When value_error then
Insert into output values (1, ‘in main error’); -- exception encountered here
End;
/
SQL>Ed p67.sql
Declare
X number (4):= 1;
Begin
Insert into output values (X, ‘before sub’);
Declare
X number (4):= 1000;
Begin
Insert into output values (X, ‘in sub’);
Exception When value_error then
Insert into output values (1, ‘in sub eror’);
End;
Insert into output values (X, ‘after sub’);
Exception When value_error then
Insert into output values (1, ‘in main error’); not allowed
End;
/
SQL>Ed p68.sql
Declare
X number (4):= 1;
Begin
Insert into output values (X, ‘before sub’); -- called
Declare
X number (4);
Begin
X:= 10000; -- error occurred
Insert into output values (X, ‘in sub’);
Exception When value_error then
Insert into output values (1, ‘in sub error’); -- called
End;
Insert into output values (X, ‘after sub’); -- called
Exception When value_error then
Insert into output values (1, ‘in main error’);
End;
/
SQL>Ed p69.sql
Declare
X number (4):= 1;
Begin
Insert into output values (X, ‘before sub’); -- called
Declare
X number (4);
Begin
X:= 10000; -- error occurred
Insert into output values (X, ‘in sub’);
End;
- 28 -
Insert into output values (X, ‘after sub’);
Exception When value_error then
Insert into output values (1, ‘in main error’); -- called
End;
/
Exceptions are 2 types
1. Pre-defined Exceptions
Available with the system
Automatically invoked by Oracle PL/SQL as required
Named exceptions 21 others un-Named exceptions 35000 errors
www.ora-code.com
2. User-defined Exceptions
Programmer created
Functional rules or business rules
Raised explicitly
SQL>Ed p70.sql
Declare
X number(4);
User_ex Exception; -- declare User-defined Exceptions
Begin
Select sal into x from emp where ename = ‘KING’;
If X> 5000 then
Raise User_ex; -- raise/define User-defined Exceptions
End if;
Insert into output values (x, ‘KING’);
Exception When User_ex then -- call User-defined Exceptions
Insert into output values (x, ‘High Sal’); -- exception encountered here
End;
/
SQL>Ed p71.sql
Declare
X number(4);
User_ex Exception; -- declare User-defined Exceptions
Pragma exception_init(User_ex,-01843); -- per-compiler directive
Begin
Select sal into x from emp where hiredate = ’10-MMM-94’;
-- confirm the error code [ora-01843 Not a Valid Month]
Exception When User_ex then -- call User-defined Exceptions
Insert into output values (X,‘ora-01843 Not a Valid Month’); -- exception encountered here
End;
/
- 29 -
PL/SQL Arrays
To store multiple elements of same datatype
Temporary PL/SQL table
1-Dimension and 2- Dimension (as cursor) allowed
For scalar or for composite datatype
Array size is dynamic
No need to Start from 0 a(1)…a(n) values/elements subscripts or index
If subscript is a constant has to be base 10. a(4)
If subscript is a variable has to be base 10 or base 2. a(x)
Base 2 or binary integer always faster than integer or base 10
Conversion of base 10 or base 2 is implicit or automatic
Range of binary integer -2 billion to +2 billion
Need not be sequential
Stored in consecutive memory locations
Oracle use Array in Encryption and decrypttion
SQL>Ed p72.sql
Declare
Type T is table of number (4) index by binary_integer; -- creation of datatype array
-- Index by binary_integer for using subscript in binary
Y T;
I binary_integer:=1; -- conversion is implicit
Begin
Y(1):= 1000;
Y(2:= 2000;
Y(3):= 3000;
While I < 4
Loop
Insert into output values (y(i),’iflex’);
I:= I+1;
End loop;
End;
/
SQL>Ed p73.sql
Declare
Type T is table of char (15) index by binary_integer;
y T;
Cursor c1 is select ename from emp;
i binary_integer:=1;
j binary_integer:=1;
Begin
For x in c1
Loop
Y(i):= x.ename;
i:=i+1;
End loop;
While j < i
- 30 -
Loop
Insert into output values (j, y (j));
j:=j+1;
End loop;
End;
/
Database Stored Objects
Stored Procedures
Global procedures
Stored in the database in the COMPILED Format make a EXE file of Procedure
Hiding the code from user
Execution be very fast
Accessed from SQL*Plus, iSQL*Plus, PL/SQL Programs, forms, Reports, Menus any front-
end tool etc.
Execution from server side [server RAM] suited for server side data processing
Only a single copy brought into server RAM for processing (Program code shared by all
users)
Parameter can be passed
Put cursor, exception within stored procedure
To modify first drop it then just recreate it.
Without dropping just to overwrite use Create or replace
Overloading of Stored procedure is not allowed
SQL>Ed p74.sql
Create or replace procedure SProc_1
As
X number (2):=10; -- no need to use Declare section
Begin
Insert into output values (X, ‘in procedure’);
End;
/
SQL>@p74.sql
Procedure created -- compiled and stored into database
SQL>execute SProc_1
SQL>Ed p75.sql
Create or replace procedure SProc_2(X number default 10)
As
Begin
Insert into output values (X, ‘in procedure’);
End;
/
SQL>@p75.sql
Procedure created
SQL>execute SProc_2(10)
SQL>Ed p76.sql
Create or replace procedure SProc_3(p number,t number,r number)
As
Intr number(6,2);
Amt number(7,2);
Begin
Intr:= p*t*r/100;
- 31 -
Amt:= p+ Intr
Insert into output values (Intr, ‘Interest’);
Insert into output values (Amt, ‘total Amount’);
Exception When value_error then
Insert into output values (1, ‘value too Large’);
End;
/
SQL>@p76.sql
Procedure created
SQL>execute SProc_3(10000,5,9)
Parameter of 3 types
In
Read only/ pass constant, variables, expressions/ call by value
In is the default value for stored procedure in Oracle
SQL>Ed p77.sql
Create or replace procedure SProc_4(X in number)
As
Begin
-- X:=100; -- not possible as X is IN variable
Insert into output values (X, ‘in procedure’);
End;
/
SQL>@p77.sql
Procedure created
Declare
X number(4):=10;
Begin
SProc_4(X); -- possible
SProc_4(5); -- possible
SProc_4(2*X+10); -- possible
End;
/
- 32 -
SProc_5(y); -- refer to same address of X variable of SProc_5
-- return the value of X=100
-- it is the Call by Reference process
Insert into output values (y, ‘after procedure’); -- y=100
End;
/
SQL>Ed p79.sql
Create or replace procedure SProc_6(X IN OUT number) -- can read from other
As
Begin
X:=X*X*X; -- possible as X is IN OUT variable
Insert into output values (X, ‘in procedure’);
End;
/
SQL>@p79.sql
Procedure created
Declare
y number(4):=10;
Begin
Insert into output values (y, ‘before procedure’); -- y=10
SProc_6(y); -- refer to same address of X variable of SProc_5
-- return the value of X=1000
-- It is the Call by Reference process
Insert into output values (y, ‘after procedure’); -- y=1000
End;
/
Spool abc
Select text from user_source where name = upper(‘SProc_6’);
Spool off
- 33 -
Stored functions
Routine that returns a value directly and compulsorily (void not accepted/null permitted)
All properties same as Stored Procedures
Can’t call at SQL Prompt
Function can’t call by itself must equate with a variable
Can be called in SQL commands
SQL>Ed p80.sql
Create or replace function SFunc_1(X number) return number
-- must return some value
As
Begin
X:=X*X*X;
End;
/
SQL>@p80.sql
Procedure created
Declare
Y number(4);
Begin
Y:= SFunc_1 (10);
Insert into output values (y, ‘after function’); -- result y=1000
End;
/
SQL>Ed p81.sql
Create or replace function SFunc_2(X number) return Boolean
As
Begin
If X>5000 then
Return true;
Else
Return false;
End if;
End;
/
SQL>@p81.sql
Procedure created
Declare
Y number(4):=&y;
Begin
If SFunc_2 (y) then
Insert into output values (y, ‘after function > 5000’);
else
- 34 -
Insert into output values (y, ‘after function <= 5000’);
End if;
End;
/
SQL>Ed p82.sql
Create or replace function SFunc_3(X number) return number
-- must return some value
As
Begin
X:=X*X*X;
End;
/
SQL>@p82.sql
Procedure created
[The library cache is managed by a least recently used (LRU) algorithm. As the cache fills,
less recently used execution paths and parse trees are removed from the library cache to make
room for the new.
– Shared SQL area /1.1.2 Shared PL/SQL area
The shared PL/SQL area stores and shares the most recently executed PL/SQL statements.
Parsed and compiled program units and procedures (functions, packages, and triggers) are
stored in this area.]
- 35 -
SQL>Ed p83.sql
Create or replace package Pack_1
As
Procedure proc_1; -- globally available if procedure in definition
Procedure Proc_2; -- globally available if procedure in definition
End;
/ -- package Definition/ Specification
- 36 -
SQL>Ed p84.sql
Create or replace package Pack_2
As
Procedure proc_1;
Procedure Proc_2;
End;
/
Create or replace package body Pack_2
As
Procedure Proc_1
Is
X number(4):=1;
Begin
Insert into output values (X, ‘1st procedure’);
X:=X+1;
End;
Procedure Proc_2
Is
X number(4):=1;
Begin
Insert into output values (X, ‘2nd procedure’);
X:=X+1;
End;
End;
/
SQL> @p84
SQL> Execute Pack_2.Proc_1 -- result X=1, X=2 X destroyed
SQL> Execute Pack_2.Proc_2 -- result X=1, X=2 X destroyed
SQL>Ed p85.sql
Create or replace package Pack_3
As
Procedure proc_1;
Procedure Proc_2;
Y number(4)=10; -- global variable in oracle
End;
/
Create or replace package body Pack_3
- 37 -
As
X number(4):=0; -- local
Procedure Proc_1
Is
Begin
Insert into output values (X, ‘1st procedure’);
X:=X+1;
End;
Procedure Proc_2
Is
Begin
Insert into output values (X, ‘2nd procedure’);
X:=X+1;
End;
End;
/
SQL> @p85
SQL> Execute Pack_3.Proc_1 -- result X=1, X=2 X remain in RAM
SQL> Execute Pack_3.Proc_2 -- result X=2, X=3 X remain in RAM
SQL>Ed p86.sql
Declare
Begin
Insert into output values (Pack_3.Y, ‘used procedure 1nc’);
Pack_3.Y:= 5;
Insert into output values (Pack_3.Y, ‘used procedure 2wc’);
End;
/
SQL> @p86
Output1 Output1
5 used procedure 1nc’
10 used procedure 2wc’
SQL>Ed p87.sql
Create or replace package Pack_3
As
Procedure proc_1;
Procedure Proc_2;
X number(4); -- don’t initialize
End;
/
Create or replace package body Pack_3
As
Procedure Proc_1
Is
Begin
Insert into output values (X, ‘1st procedure’);
X:=X+1;
End;
Procedure Proc_2
Is
Begin
Insert into output values (X, ‘2nd procedure’);
- 38 -
X:=X+1;
End;
Begin
Select count(*) into X from output
End;
/
- 39 -
History Table – in which table the data Inserted from parent table deleted data
Shadow Table/ History Table both can be maintained in Update trigger
Automatic updating of related table
:new/:old variables Only in Row level trigger
To drop
drop trigger trigger_name; -- table deletion trigger drops
Alter Trigger trigger_name Disable|enable;
System table USER_TRIGGERS
SQL>Ed p88.sql
Create or replace trigger Trg_1
BEFORE INSERT
ON EMP -- statement level trigger only once fired [default]
BEGIN
Insert into output values (1, ‘Trigger started’);
End;
/
SQL>@p88
Trigger created
SQL>Ed p89.sql
Create or replace trigger Trg_2
BEFORE INSERT
ON EMP
FOR EACH ROW -- row level trigger fired for every row
BEGIN
Insert into output values (1, ‘Trigger started’);
End;
/
SQL>Ed p90.sql
Create or replace trigger Trg_3
BEFORE INSERT
ON EMP
FOR EACH ROW
BEGIN
Insert into output values (:new.empno, new.ename);
-- Oracle created trigger Variable access the new value
-- Used: new.col_name Only in Row level trigger
End;
/
SQL>Ed p91.sql
CREATE OR REPLACE TRIGGER Trg_4
BEFORE INSERT ON EMP
FOR EACH ROW
BEGIN
: NEW.ENAME:= UPPER (:NEW.ENAME); -- data Cleansing (before insert)
END;
/
SQL>Ed p92.sql
Create or replace trigger Trg_5
- 40 -
BEFORE INSERT
ON EMP
FOR EACH ROW
BEGIN
Update dept set sal = sal +:new.sal where deptno =:new.deptno;
End;
/
SQL>Ed p93.sql
Create or replace trigger Trg_6
BEFORE delete
ON EMP
BEGIN
Insert into output values (1,’deleted’);
End;
/
SQL>Ed p94.sql
Create or replace trigger Trg_7
BEFORE delete
ON EMP for each row
BEGIN
Insert into output values (:old.empno, :old.ename);
-- oracle created trigger Variable access the old value
-- Used: old.col_name Only in Row level trigger
Update dept set sal = sal -:old.sal where deptno =:old.deptno;
End;
/
SQL>Ed p95.sql
Create or replace trigger Trg_8
BEFORE delete
ON EMP for each row
BEGIN
Insert into output values (:old.rownum, ’row deleted’);
End;
/
SQL>Ed p96.sql
Create or replace trigger Trg_9
BEFORE update
ON EMP
BEGIN
Insert into output values (1, ’row updated’);
End;
/
SQL>Ed p97.sql
Create or replace trigger Trg_10
BEFORE update
ON EMP for each row
BEGIN
Insert into output values (:old.empno,:old.ename);
- 41 -
Insert into output values (:new.empno,:new.ename);
End;
/
In oracle using update trigger fire insert trigger and delete trigger in continuity
– known as Cascading Triggers if one failed entire transaction will be rolled back
If the end trigger is an update trigger > Error: Table is undergoing mutation
SQL>Ed p98.sql
Create or replace trigger Trg_11
BEFORE update
ON EMP for each row
BEGIN
Update dept set sal = sal +:new.sal - :old.sal where deptno =:old.deptno;
End;
/
- 42 -
SQL>Create table customers(
Custid number(4),
Person person_type);
- 43 -