+ All Categories
Home > Documents > Oracle 10g PL SQL

Oracle 10g PL SQL

Date post: 11-Apr-2015
Category:
Upload: emailtorakesh
View: 843 times
Download: 2 times
Share this document with a friend
43
Rakesh Chakrabarti [email protected] Oracle 10g (grid computing) PL/SQL Introduction Procedural Language SQL Programming Language of Oracle Used for server side database processing Can be called from anywhere (any front-end) like: SQL*Plus forms reports menus graphics Root in PASCAL programming 4 GL (supports OOPS) Case insensitive Block level language Limitation: Screen i/p or o/p not allowed SQL commands allowed: Insert update delete Select Rollback commit savepoint DDL/DCL/SQL*Plus commands not allowed: Create drop alter Grant revoke unless use dynamic SQL Execution is top to bottom left to right Entire program goes into buffer/ keeps getting overwritten/ to re execute enter / Structure of PL/SQL block [ Declare -- Single Line comment /* Multiple line Comment */ Begin …. … Processing … {PL/SQL Block sub-block or nesting of block} End; / (Terminator of program first column of last line @the end first character) ] = PL/SQL Block 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 -
Transcript
Page 1: Oracle 10g PL SQL

Rakesh Chakrabarti [email protected]

Oracle 10g (grid computing) PL/SQL

Introduction

Procedural Language SQL Programming Language of Oracle Used for server side database processing Can be called from anywhere (any front-end) like: SQL*Plus forms reports menus

graphics Root in PASCAL programming 4 GL (supports OOPS) Case insensitive Block level language Limitation: Screen i/p or o/p not allowed SQL commands allowed: Insert update delete Select Rollback commit savepoint DDL/DCL/SQL*Plus commands not allowed: Create drop alter Grant revoke unless use

dynamic SQL Execution is top to bottom left to right Entire program goes into buffer/ keeps getting overwritten/ to re execute enter /

Structure of PL/SQL block[Declare-- Single Line comment/* Multiple lineComment */Begin …. … Processing …{PL/SQL Block sub-block or nesting of block} End; / (Terminator of program first column of last line @the end first character)] = PL/SQL Block

Advantage of sub-block:Global and local variables can be declaredData hiding as encapsulationEfficient error handling (exception)

Instructions:Create an output table and put all programs output in Output TableAs the result can’t be shown into the screen send it to Output TableTable Output: Create table output (File number (4), sec char (15));

Program No 1. p1.sqlSQL>Ed p1.sqlBeginInsert into output values (1,’iflex’);End;/SQL> @p1-- compiles and execute

- 1 -

Page 2: Oracle 10g PL SQL

PL/SQL Procedure successfully completedSQL>select * from output;

Program No 2. p2.sqlSQL>Ed p2.sqlDeclareX number(4);-- store a null value take 1 bytes in RAM no garbage collection in PL/SQLBeginX:= 100; -- := assignment operatorInsert into output values (x,’iflex’);End;/

Program No 3. p3.sqlSQL>Ed p3.sqlDeclareX number(4) := 100;-- declare and assign value at same time [recommended]BeginInsert into output values (x,’iflex’);End;/

Program No 4. p4.sqlSQL>Ed p3.sqlDeclareX number(4);BeginX:= &x; -- possible because common compiler for SQL SQL*Plus PL/SQLInsert into output values (x,’iflex’);End;/SQL>@p4Enter value of x: 100

& works before compilation not at run time similar #define in COnly for SQL*Plus Prompt/ Debugging | else where not recommended

Program No 5. p5.sql Integration of SQL*Plus + PL/SQL + SQLSQL>Ed p5.sqlClea screAccept x number prompt “Please enter the Salary”DeclareX number(4);BeginX:= &x;Insert into output values (x,’iflex’);End;/Undefine xSelect * from output;Delete output;

- 2 -

Page 3: Oracle 10g PL SQL

Program No 6. p6.sqlSQL>Ed p6.sqlClea screAccept x number prompt “Please enter the Name”DeclareX char(15);BeginX:= &x;|X:= ‘&x’; |X:= &x;Insert into output values (1,x);End;/Undefine xSelect * from output;Delete output;

@p6Please 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.sqlSQL>Ed p7.sqlDeclareX constant number(4) := 1000;-- constant must be define at declare section otherwise it be an errorBeginInsert into output values (x,’iflex’);End;/

Program No 8. p8.sqlSQL>Ed p8.sqlDeclareX char(15);Y number(7);Z number(7);BeginX:= ‘&ename’;Y:= &salary;Z:= y*0.4;

Insert into output values (Y,X);Insert into output values (Z,’HRA’);

End;/

- 3 -

Page 4: Oracle 10g PL SQL

Program No 9. p9.sqlSQL>Ed p9.sqlSet verify offSet serveroutput on-- serveroutput on[off] SQL*plus commandDeclareX char(15);Y number(7,2);Z number(6,2);BeginX:= '&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);

-- DBMS_OUTPUT is an Oracle supplied package not a part of standard PL/SQL command-- Collection of procedures and functions-- Helps to make PL/SQL interactive-- PUT_LINE is a procedure of DBMS_OUTPUT package-- DBMS_OUTPUT.PUT_LINE only for SQL*Plus PromptEnd;/undefine X,Y,Z

Program No 10. p10.sqlSQL>Ed p10.sqlDeclareZ number(4);BeginSelect sal into Z from emp where ename = ‘KING’;-- sal into Z get data from processing assuming for only 1 record-- for multiple rows require an arrayInsert into output values (Z,’KING’);End;/

Program No 11. p11.sqlSQL>Ed p11.sqlDeclareZ number(4);Y CHAR(15);BeginSelect sal, job into Z,Y from emp where ename = ‘KING’;-- sal, job into Z,Y SEQUENCE is most important and data type (precession)Insert into output values (Z,Y);End;/

- 4 -

Page 5: Oracle 10g PL SQL

Program No 12. p12.sqlSQL>Ed p12.sqlDeclareZ emp.sal%type;Y emp.job%type;-- Exact match if column precession changes then it helpsBeginSelect sal, job into Z,Y from emp where ename = ‘KING’;Insert into output values (Z,Y);End;/

Program No 13. p13.sqlSQL>Ed p13.sqlDeclareZ emp%rowtype;-- Z is a structure like emp entire record in one variable -- if table structure changes no problem-- Advantage of Structure: X emp%rowtype; X:=Z; contents of Z to X Helps to data transfer-- X.sal = Z.sal individual content copy

BeginSelect * from Z where ename = ‘KING’;Insert into output values (Z.sal,Z.job);End;/

Program No 14. p14.sqlSQL>Ed p14.sqlDeclareX emp%rowtype;BeginSelect * into X from emp where ename = ‘KING’;-- Select ename,sal,job into X.ename, X.sal, X.job from emp where ename = ‘KING’;Insert into output values (X.sal,X.job);End;/

Program No 15. p15.sqlSQL>Ed p15.sqlDeclareType pqr is record( A emp.sal%type;

B emp.job%type; );X pqr; -- User defined structure/data type or abstract data type-- Y pqr; Y: = X;BeginSelect sal, job into X from emp where ename = ‘KING’;Insert into output values (X.A,X.B);End;/

- 5 -

Page 6: Oracle 10g PL SQL

Program No 16. p16.sqlSQL>Ed p16.sqlDeclareType 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-structureBeginSelect 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;/

Program No 17. p17.sqlSQL>Ed p17.sqlDeclareX number(4);BeginSelect sal into X from emp where ename = ‘KING’;

If x>4000 thenInsert into output values (X, ‘High sal’);

End if;-- If statementEnd;/

Program No 18. p18.sqlSQL>Ed p18.sqlDeclareX number(4);BeginSelect sal into X from emp where ename = ‘KING’;

If x>4000 thenInsert into output values (X, ‘High sal’);

ElseInsert into output values (X, ‘Low sal’);

End if;-- If-else statementEnd;/

Program No 19. p19.sqlSQL>Ed p19.sqlDeclarex number(4);BeginSelect sal into X from emp where ename = ‘KING’;

- 6 -

Page 7: Oracle 10g PL SQL

If x>4000 thenInsert into output values (X, ‘High sal’);

Elsif x<4000 thenInsert into output values (X, ‘Low sal’);

ElseInsert 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;

Program No 20. p20.sqlSQL>Ed p20.sqlDeclarex Boolean;-- Boolean variable logical data type [True, False, Null]-- Only in PL/SQL cant store Boolean in TableBeginx:= true;If x then-- directly use Boolean variable

Insert into output values (1, ‘Delhi’);End if;End;/

Program No 21. p21.sqlSQL>Ed p21.sqlDeclarex Boolean;Beginx:= false;If not x then

Insert into output values (1, ‘Delhi’);End if;End;/

- 7 -

Page 8: Oracle 10g PL SQL

Use Loops - For repetitive processing

Program No 22. p22.sqlSQL>Ed p22.sqlDeclareX number(4):= 1;Begin -- While loop no increment/decrement operatorWhile X<10loop

Insert into output values (X, ‘in while loop’);X;=X+1;-- if no condition found while goes for infinite loop-- to kill the process request the server administrator

End loop;End;/X=1…9

Program No 23. p23.sqlSQL>Ed p23.sqlDeclareX number(4):= 1;Y number(4):= 1;

Begin -- While loop no increment/decrement operatorWhile X<10Loop

While Y<10LoopInsert 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 = 1Y =1…9X = 2….9

Program No 24. p24.sqlSQL>Ed p24.sqlDeclareX number(4):= 1;Y number(4):= 1;Begin -- While loop no increment/decrement operatorWhile X<10

- 8 -

Page 9: Oracle 10g PL SQL

LoopWhile Y<XLoopInsert 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 =1X = 2 Y =2……………..X = 8 Y =8X = 9

Program No 25. p25.sqlSQL>Ed p25.sqlDeclareX number(4):= 1;Y number(4);Begin While X<10Loop

Y:=&SAL;-- PROMPT FOR ONLY ONNCE &SALInsert into output values (Y, ‘in X loop’);X:=X+1;

End loop;End;/

Program No 26. p26.sqlSQL>Ed p26.sqlDeclareX number(4):= 1;Begin While X<10Loop

Insert into output values (X, ‘in X loop’);If x>5 thenExit;End if;X:=X+1;

End loop;End;/

X = 1...6

- 9 -

Page 10: Oracle 10g PL SQL

Program No 27. p27.sqlSQL>Ed p27.sqlDeclareX number(4):= 1;Begin While X<10Loop

Insert into output values (X, ‘in X loop’);Exit when x>5;-- Exit when conditionX:=X+1;

End loop;End;/

X = 1...6

Program No 28. p28.sqlSQL>Ed p28.sqlDeclareX number(4):= 100;Begin Loop

Insert into output values (X, ‘in X loop’);Exit when x>5;-- If only loop … end loop; then go for infinite loop-- loop … end loop and Exit when condition make a do-while loop

X:=X+1;End loop;End;/

Program No 29. p29.sqlSQL>Ed p29.sqlDeclareX number(4):= 1;-- optional declaration-- for loop variable need not be declared scope within the for blockBegin For X in 1..10Loop

Insert into output values (X, ‘X for loop’);-- For Loop Convenience of Programmer-- Auto increment of variable only for integer (no float)-- Always increment/decrement by 1 (step value not allowed)-- .. Only two dots-- X:=X+2;-- Gives an error for loop variable is read only can’t be initialized within the loop

End loop;End;/

- 10 -

Page 11: Oracle 10g PL SQL

X = 1..10

Program No 30. p30.sqlSQL>Ed p30.sqlDeclareX number(4):= 100;Begin

Insert into output values (X, ‘X before loop’); -- value of global XFor X in 1..10

LoopInsert into output values (X, ‘X for loop’); -- value of local X

End loop;Insert into output values (X, ‘X after loop’); -- value of global X

End;/X = 100X = 1..10X = 100

Program No 31. p31.sqlSQL>Ed p31.sqlDeclareX number(4):= 100; -- global XBegin

For X in 1..&y -- local XLoopInsert into output values (X, ‘X for loop’); -- value of local XEnd loop;

End;/

Program No 32. p32.sqlSQL>Ed p32.sqlDeclareX number(4):= 100; -- global XBegin

For X in &X ..&Y -- local X &X = substitution text-- &X..&Y asks for “Enter value for X.:” it gives error as . is not a valid character-- Solution = &X ..&Y or &X...&YLoopInsert into output values (X, ‘X for loop’); -- value of local XEnd loop;

End;/

Program No 33. p33.sqlSQL>Ed p33.sqlDeclareX number(4):= 1;Begin For X in 10..1-- o/p is nothing wouldn’t enter the loopLoop

- 11 -

Page 12: Oracle 10g PL SQL

Insert into output values (X, ‘X for loop’);End loop;End;/

Program No 34. p34.sqlSQL>Ed p34.sqlDeclareX number(4):= 100;Begin For X in reverse 1..10-- use reverse order to decrement Loop

Insert into output values (X, ‘X for loop’);End loop;End;/X= 10..1

Program No 35. p35.sqlSQL>Ed p35.sqlDeclareX number(4):= 100;Begin For X in 1..10Loop

For Y in 1..xLoopInsert into output values (Y, ‘Y for loop’);End loop;

End loop;End;/

Program No 36. p36.sqlSQL>Ed p36.sqlDeclareX number(4):= 1;Begin

Insert into output values (X, ‘A’);Goto abc; -- Goto statement Transfer of control [not recommended]

-- use in deeply nested loop, come out from IF construct-- To emulate continue stmt. Of ‘C’

<<pqr>>Insert into output values (X, ‘B’);X: X+1;

<<abc>>Insert into output values (X, ‘C’);If x < 3 thenGoto pqr; -- large no. of GOTO stmt. Known as spagotte code.

End if;End;/

- 12 -

Page 13: Oracle 10g PL SQL

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.sqlSQL>Ed p37.sqlDeclareX number (4):= 100;Begin Insert into output values (X, ‘before sub’);

DeclareY number (4):= 200;BeginX; =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 allowedEnd;/

Program No 38. p38.sqlSQL>Ed p38.sqlDeclareX number (4):= 100;Begin Insert into output values (X, ‘before sub’); -- global variable

DeclareX number (4):= 200;BeginInsert into output values (X, ‘in sub’); -- local variableEnd;

Insert into output values (X, ‘after sub’); -- global variableEnd;/

- 13 -

Page 14: Oracle 10g PL SQL

Program No 39. p39.sqlSQL>Ed p39.sql<<abc>> -- create a labelDeclareX number (4):= 100;Begin Insert into output values (X, ‘before sub’); -- global variable X

DeclareX number(4):= 200;BeginInsert into output values (abc.X, ‘in sub’); -- global variable XEnd;

End;/

<<abc>>Declare 1………x….;Begin………….;

Declare 2………x….; call abc.x will call 1st block’s xBegin………….;

Declare 3………x….; call abc.x will call 2nd block’s xBegin………….;End;

End;

End;

<<abc>>Declare 1………x….;Begin………….;

<<pqr>>Declare 2………x….; call abc.x will call 1st block’s xBegin………….;

Declare 3………x….; call abc.x will call 1st block’s xBegin………….;End;

End;

- 14 -

Page 15: Oracle 10g PL SQL

End;Declare 1………x….;Begin………….;

<<abc>>Declare 2………x….; can’t call 3rd block’s pqr.x even with labels declaredBegin………….; End;<<pqr>>Declare 3………x….; can’t call 2nd block’s abc.x with labels declaredBegin………….;End;

End;http://in.briefcase.yahoo.com/emailtorakesh

--------------------------------------------------------------------------------------------------------------------

- 15 -

Page 16: Oracle 10g PL SQL

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.sqlSQL>Ed p40.sqlDeclareCursor 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 valueBeginOpen c1; -- execute select statement and set cursor pointer points to first row/recordFor 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 tableEnd loop; -- 5 times in loop every time x is overwrittenClose 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.sqlDeclareCursor 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 -

Page 17: Oracle 10g PL SQL

Program No 42. p42.sql -- not a recommended solution. Use Cursor Attributes/Functions:SQL>Ed p42.sqlDeclareCursor 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..zFetch c1 to x;Insert into output values (x.empno, x.ename);

End loop; Close c1;End;/

Cursor Attributes/Functions:Program No 43. p43.sqlSQL>Ed p43.sqlDeclareCursor 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 idExit; -- 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.sqlSQL>Ed p44.sqlDeclareCursor 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 -

Page 18: Oracle 10g PL SQL

/Program No 45. p45.sqlSQL>Ed p45.sqlDeclareCursor 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 farInsert into output values (y, x.ename);

End loop;Close c1;End;/

Program No 46. p46.sqlSQL>Ed p46.sqlDeclareCursor c1 is select * from EMP order by sal; x emp%rowtype;Begin

If c1%isopen then -- return a Boolean true value if cursor is already openClose c1;

End if;Open c1;

LoopFetch c1 to x;Exit when c1%notfound;Insert into output values (x.empno, x.ename);

End loop;Close c1;End;/

Program No 47. p47.sqlSQL>Ed p47.sqlDeclareCursor c1 is select ename,sal from EMP;

x c1%rowtype; -- structure of x like ‘select ename, sal from EMP’Begin

Open c1;Loop

Fetch c1 to x; Exit when c1%notfound;

Insert into output values (x.sal, x.ename); End loop;

Close c1;End;/

- 18 -

Page 19: Oracle 10g PL SQL

Program No 48. p48.sql Integration of Cursor with loop *only in Oracle PL/SQLSQL>Ed p48.sqlDeclareCursor c1 is select ename,sal from EMP; BeginFor 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;/

Program No 49. p49.sqlSQL>Ed p49.sqlDeclareCursor c1 is select * from EMP where deptno = 1; -- deptno = &deptnoBeginFor x in c1Loop

Insert into output values (x.sal, x.ename); End loop;End;/

Parameter to a CursorProgram No 50. p50.sqlSQL>Ed p50.sqlDeclareCursor c1 (dd number) is select * from EMP where deptno = dd; Begin

For x in c1 (1) -- c1 (&d1) also taken from runtimeLoop

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;/

Program No 51. p51.sqlSQL>Ed p51.sqlDeclareCursor c1 (dd number, ss number) is select * from EMP where deptno = dd and sal > ss; Begin

For x in c1 (1, 5000) -- multiple parameter passing separated by commaLoop

Insert into output values (x.sal, x.ename); End loop;

End;

- 19 -

Page 20: Oracle 10g PL SQL

/Program No 52. p52.sqlSQL>Ed p52.sqlDeclareCursor c1 (dd number default 1) is select * from EMP where deptno = dd ; Begin

For x in c1 -- specify default value for parameterLoop

Insert into output values (x.sal, x.ename); End loop;

End;/pfile Init.ora total parameter is 314 in Oracle 10gOPEN_CURSOR = 300 – to manage cursor opened per session

Program No 53. p53.sqlSQL>Ed p53.sqlDeclareCursor c1 is select * from EMP; Cursor c2 is select * from DEPT;

BeginFor x in c1Loop

For y in c2Loop

If x.deptno = y.deptno thenInsert 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.sqlDeclareCursor c1 is select * from EMP; Cursor c2 (dd number) is select * from DEPT where deptno = dd;

BeginFor x in c1Loop

For y in c2 (x.deptno)Loop

Insert into output values (y.empno,x.dname); End loop;

End loop;End;/

- 20 -

Page 21: Oracle 10g PL SQL

Program No 55. p55.sql --fastest way [use joins] recommendedSQL>Ed p55.sqlDeclareCursor c1 is select empno,deptno from EMP,dept where dept.deptno = emp.deptno; Begin

For x in c1Loop

Insert into output values (x.empno,x.dname); End loop;

End;/

Program No 56. p56.sqlSQL>Ed p56.sqlDeclareCursor c1 is select ename, sal+1 SALARY from EMP; -- For computed fields, expressions, functions need to provide alias for virtual columnBegin

For x in c1Loop

Insert into output values (x.SALARY, x.ename); End loop;

End;/

Program No 56. p56.sqlSQL>Ed p56.sqlDeclareCursor c1 is select * from EMP; Begin

For x in c1Loop

Update EMP set sal = sal+1;-- For each time in loop all rows of sal column of EMP updated by 1;

End loop;End;/

Program No 57. p57.sqlSQL>Ed p57.sqlDeclareCursor c1 is select * from EMP; Begin

For x in c1Loop

If x.sal > 7000 thenUpdate EMP set sal = sal+1; -- For each time in loop if construct is true -- Then all rows of sal column of EMP updated by 1;End if;

End loop;End;

- 21 -

Page 22: Oracle 10g PL SQL

/

Program No 58. p58.sqlSQL>Ed p58.sqlDeclareCursor c1 is select * from EMP; Begin

For x in c1Loop

If x.sal > 7000 thenUpdate EMP set sal = sal+1 where empno = x.empno; -- Possibility of duplicityEnd if;

End loop;End;/

Program No 59. p59.sqlSQL>Ed p59.sqlDeclareCursor c1 is select * from EMP for update; -- for update [wait 60]-- If any other user modifies data then might be row-id changes-- As cursor works upon row-id so using for update is mandatoryBegin

For x in c1Loop

If x.sal > 7000 thenUpdate EMP set sal = sal+1 where current of c1; -- Update the correspondence not all -- solve Possibility of duplicity-- Also useful for Delete [Delete EMP where current of c1;]-- Use where current of cursor_name compulsory is for updateEnd if;

End loop;Commit;

End;/

Cursor two typesExplicit – programmer created, declaring done explicit as CURSOR C1, Used for storing/handling/processing multiple rows, Used for storing data temporarily (in RAM), Locking Rows ManuallyDeclareCursor c1 is select * from EMP for update;Begin

Open c1;Close c1;

End;/Implicit – Oracle Created, System Cursor, check the status of last DML statements

- 22 -

Page 23: Oracle 10g PL SQL

(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.sqlSQL>Ed p60.sqlDeclareX 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 -

Page 24: Oracle 10g PL SQL

Rony_CURSOR ex1

DECLAREV_RAD NUMBER(5,2);V_AREA NUMBER(5,2);CURSOR mycur IS SELECT radius from RAD WHERE radius > 3 AND radius <7;

BEGINOPEN mycur;

LOOPFETCH 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 ex2DECLAREV_EMPNONUMBER(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 ex3DECLAREV_EMPNONUMBER(4);V_TEMP NUMBER(2);CURSOR EMP_CHK IS SELECT EMPNO FROM EMP2;BEGIN

OPEN EMP_CHK;V_TEMP := 0;

LOOPFETCH 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 -

Page 25: Oracle 10g PL SQL

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 block1. too_many_rows2. no_data_found3. value_error -- for variable/value/data4. invalid_number -- for column type5. zero_divide6. others -- default Exception

Program No 61. p61.sqlSQL>Ed p61.sqlDeclareX number (4);Begin

Select sal into x from emp where ename = ‘KING’;Insert into output values (X, ‘KING’);

Exception when too_many_rows then -- must be at the end of the blockDBMS_OUTPUT.PUT_LINE ('Duplicate Entry for the Name KING');End;/

Program No 61. p61.sqlSQL>Ed p61.sqlDeclareX number (4);Begin

Select sal into x from emp where ename = ‘KINGA’;Insert into output values (X, ‘KINGA’);

Exception when no_data_found thenDBMS_OUTPUT.PUT_LINE ('No Entry for the Name KING');End;/

Program No 62. p62.sqlSQL>Ed p62.sqlDeclareX number (4);Begin

X:= 10000; -- X: = ‘Pune’; for Datatype mismatch use value_errorInsert into output values (X, ‘KINGA’);

- 25 -

Page 26: Oracle 10g PL SQL

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 precisionDBMS_OUTPUT.PUT_LINE (‘Value is to High’);End;/Program No 63. p63.sqlSQL>Ed p63.sqlDeclareX number (4);Begin

X: = Pune; -- assume Pune as variable-- for variable not found no exception available in Oracle

End;/

Program No 64. p64.sqlSQL>Ed p64.sqlDeclareX char (4);Begin

X: = 100; -- no exception as character conversion done automatic in OracleEnd;/

Program No 65. p65.sqlSQL>Ed p65.sqlDeclareX number (4);Begin

Insert into output values (‘Pune’, ‘City’); -- try to insert char value in number columnException when invalid_number thenDBMS_OUTPUT.PUT_LINE (‘Pune is not Number value for Number Column’);End;/

Program No 66. p66.sqlSQL>Ed p66.sqlDeclareX number (4):= 30;Y number (4):= 0; -- Y number(4); x:=x/y;divide by null returns nullBegin

X:= X/Y;Exception when zero_divide thenDBMS_OUTPUT.PUT_LINE (‘Can’t Divide by 0);End;/

- 26 -

Page 27: Oracle 10g PL SQL

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 OracleY:= 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.DeclareX 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

DeclareX number (4):= 10000;BeginException When value_error then Insert into output values (1, ‘in sub error’); -- exception not encountered

- 27 -

Page 28: Oracle 10g PL SQL

End;Exception When value_error then Insert into output values (1, ‘in main error’); -- exception encountered hereEnd;/SQL>Ed p67.sqlDeclareX number (4):= 1;Begin Insert into output values (X, ‘before sub’);

DeclareX number (4):= 1000;BeginInsert 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 allowedEnd;/

SQL>Ed p68.sqlDeclareX number (4):= 1;Begin

Insert into output values (X, ‘before sub’); -- calledDeclareX number (4);BeginX:= 10000; -- error occurredInsert into output values (X, ‘in sub’);Exception When value_error then Insert into output values (1, ‘in sub error’); -- calledEnd;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.sqlDeclareX number (4):= 1;Begin

Insert into output values (X, ‘before sub’); -- calledDeclareX number (4);BeginX:= 10000; -- error occurredInsert into output values (X, ‘in sub’);End;

- 28 -

Page 29: Oracle 10g PL SQL

Insert into output values (X, ‘after sub’);Exception When value_error then Insert into output values (1, ‘in main error’); -- calledEnd;/Exceptions are 2 types1. 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.com2. User-defined Exceptions

Programmer created Functional rules or business rules Raised explicitly

SQL>Ed p70.sqlDeclareX number(4);User_ex Exception; -- declare User-defined ExceptionsBegin Select sal into x from emp where ename = ‘KING’;If X> 5000 thenRaise User_ex; -- raise/define User-defined ExceptionsEnd if;Insert into output values (x, ‘KING’);Exception When User_ex then -- call User-defined ExceptionsInsert into output values (x, ‘High Sal’); -- exception encountered hereEnd;/

Give a name to un-Named exceptions using User-defined Exceptions

SQL>Ed p71.sqlDeclareX number(4);User_ex Exception; -- declare User-defined ExceptionsPragma exception_init(User_ex,-01843); -- per-compiler directiveBegin 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 ExceptionsInsert into output values (X,‘ora-01843 Not a Valid Month’); -- exception encountered hereEnd;/

- 29 -

Page 30: Oracle 10g PL SQL

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.sqlDeclareType T is table of number (4) index by binary_integer; -- creation of datatype array

-- Index by binary_integer for using subscript in binaryY T;I binary_integer:=1; -- conversion is implicitBeginY(1):= 1000;Y(2:= 2000;Y(3):= 3000;

While I < 4LoopInsert into output values (y(i),’iflex’);I:= I+1;End loop;

End;/SQL>Ed p73.sqlDeclareType 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;BeginFor x in c1Loop

Y(i):= x.ename;i:=i+1;

End loop;While j < i

- 30 -

Page 31: Oracle 10g PL SQL

LoopInsert into output values (j, y (j));j:=j+1;End loop;

End;/Database Stored ObjectsStored 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.sqlCreate or replace procedure SProc_1As

X number (2):=10; -- no need to use Declare sectionBeginInsert into output values (X, ‘in procedure’);End;

/SQL>@p74.sql

Procedure created -- compiled and stored into databaseSQL>execute SProc_1

SQL>Ed p75.sqlCreate or replace procedure SProc_2(X number default 10)As

BeginInsert into output values (X, ‘in procedure’);End;

/SQL>@p75.sql

Procedure createdSQL>execute SProc_2(10)

SQL>Ed p76.sqlCreate or replace procedure SProc_3(p number,t number,r number)As

Intr number(6,2);Amt number(7,2);

BeginIntr:= p*t*r/100;

- 31 -

Page 32: Oracle 10g PL SQL

Amt:= p+ IntrInsert 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 createdSQL>execute SProc_3(10000,5,9)

Parameter of 3 types

InRead only/ pass constant, variables, expressions/ call by valueIn is the default value for stored procedure in Oracle

SQL>Ed p77.sqlCreate or replace procedure SProc_4(X in number)As

Begin-- X:=100; -- not possible as X is IN variableInsert into output values (X, ‘in procedure’);End;

/SQL>@p77.sql

Procedure created

DeclareX number(4):=10;BeginSProc_4(X); -- possibleSProc_4(5); -- possibleSProc_4(2*X+10); -- possibleEnd;/

Out Write only/ variables onlySQL>Ed p78.sqlCreate or replace procedure SProc_5(X OUT number) -- can read from otherAs

BeginX:=100; -- possible as X is OUT variableInsert into output values (X, ‘in procedure’);End;

/SQL>@p78.sql

Procedure createdDeclarey number(4):=10;BeginInsert into output values (y, ‘before procedure’); -- y=10

- 32 -

Page 33: Oracle 10g PL SQL

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=100End;/

In Out Read & Write

SQL>Ed p79.sqlCreate or replace procedure SProc_6(X IN OUT number) -- can read from otherAs

BeginX:=X*X*X; -- possible as X is IN OUT variableInsert into output values (X, ‘in procedure’);End;

/SQL>@p79.sql

Procedure created

Declarey number(4):=10;BeginInsert into output values (y, ‘before procedure’); -- y=10SProc_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=1000End;/

Select * from user_objects where object_type = upper(‘Procedure’);Select * from user_source;Select text from user_source where name = upper(‘SProc_6’);

Spool abcSelect text from user_source where name = upper(‘SProc_6’);Spool off

select distinct type from user_source;select distinct type from all_source;select distinct type from dba_source;

- 33 -

Page 34: Oracle 10g PL SQL

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.sqlCreate or replace function SFunc_1(X number) return number-- must return some valueAs

BeginX:=X*X*X;End;

/SQL>@p80.sql

Procedure created

DeclareY number(4);BeginY:= SFunc_1 (10);Insert into output values (y, ‘after function’); -- result y=1000End;/

SQL>Ed p81.sqlCreate or replace function SFunc_2(X number) return BooleanAsBegin

If X>5000 then Return true;ElseReturn false;End if;

End;/SQL>@p81.sql

Procedure created

DeclareY number(4):=&y;Begin

If SFunc_2 (y) thenInsert into output values (y, ‘after function > 5000’);else

- 34 -

Page 35: Oracle 10g PL SQL

Insert into output values (y, ‘after function <= 5000’);End if;

End;/

SQL>Ed p82.sqlCreate or replace function SFunc_3(X number) return number-- must return some valueAs

BeginX:=X*X*X;End;

/SQL>@p82.sql

Procedure created

SQL>select SFunc_3(4) from dual;SFunc_3(4)64

Packages (stored object) Collection of procedures and functions Package resides for the session from its first call in Server side RAM or till Oracle Applies

LRU Algorithm Group together the related procedures and functions into a package Make a call to any one procedure or function and the entire package loaded into the

server RAM Faster Execution All properties same as Stored Procedures Within the package multiple Procedure or Function can be overloaded if the datatype

parameter passing is different. No two procedures and Functions can share same name Privileges as User-Sys relation globally available if procedure in definition/ locally available if procedure in package body Variable are still exist in PGA by Oracle though LRU Algorithm applies. Put User defined Exception in Package Package Definition and Package body can created separately in separate file.

[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 areaThe 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 -

Page 36: Oracle 10g PL SQL

SQL>Ed p83.sqlCreate or replace package Pack_1AsProcedure proc_1; -- globally available if procedure in definitionProcedure Proc_2; -- globally available if procedure in definitionEnd;/ -- package Definition/ Specification

Create or replace package body Pack_1As

Procedure Proc_1 -- can call Proc_3 but cannot call Proc_2IsBeginInsert into output values (1, ‘1st procedure’);Proc_3;-- Proc_2; not possible Compilation error[Forward Declaration]End;Procedure Proc_2 -- can call Proc_3 and Proc_1IsBeginInsert into output values (2, ‘2nd procedure’);End;Procedure Proc_3 -- locally available if procedure in package body-- Only available in body call by another procedure in package-- can’t call as SQL> Execute Pack_1.Proc_3IsBeginInsert into output values (2, ‘2nd procedure’);End;

End;/SQL> @p83SQL> Execute Package_name.Procedure_name -- can’t execute package

Use package in other proceduresDeclare………..Begin

Package_name.Procedure_name [(parameter)];End;/

- 36 -

Page 37: Oracle 10g PL SQL

SQL>Ed p84.sqlCreate or replace package Pack_2AsProcedure proc_1;Procedure Proc_2;End;/Create or replace package body Pack_2As

Procedure Proc_1IsX number(4):=1;BeginInsert into output values (X, ‘1st procedure’);X:=X+1;End;Procedure Proc_2IsX number(4):=1;BeginInsert into output values (X, ‘2nd procedure’);X:=X+1;End;

End;/SQL> @p84SQL> Execute Pack_2.Proc_1 -- result X=1, X=2 X destroyedSQL> Execute Pack_2.Proc_2 -- result X=1, X=2 X destroyed

Use package in other proceduresDeclare………..Begin

Package_name.G_Variable_name:= value;End;/

SQL>Ed p85.sqlCreate or replace package Pack_3AsProcedure proc_1;Procedure Proc_2;Y number(4)=10; -- global variable in oracleEnd;/Create or replace package body Pack_3

- 37 -

Page 38: Oracle 10g PL SQL

AsX number(4):=0; -- localProcedure Proc_1IsBeginInsert into output values (X, ‘1st procedure’);X:=X+1;End;Procedure Proc_2IsBeginInsert into output values (X, ‘2nd procedure’);X:=X+1;End;

End;/SQL> @p85SQL> Execute Pack_3.Proc_1 -- result X=1, X=2 X remain in RAMSQL> Execute Pack_3.Proc_2 -- result X=2, X=3 X remain in RAM

SQL>Ed p86.sqlDeclareBegin

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> @p86Output1 Output1 5 used procedure 1nc’10 used procedure 2wc’

SQL>Ed p87.sqlCreate or replace package Pack_3AsProcedure proc_1;Procedure Proc_2;X number(4); -- don’t initializeEnd;/Create or replace package body Pack_3As

Procedure Proc_1IsBeginInsert into output values (X, ‘1st procedure’);X:=X+1;End;Procedure Proc_2IsBeginInsert into output values (X, ‘2nd procedure’);

- 38 -

Page 39: Oracle 10g PL SQL

X:=X+1;End;

BeginSelect count(*) into X from output

End;/

Overloading using PackageSQL>Ed p88.sqlCreate or replace package Pack_4AsFunction Func_1(s number) return number;Function Func_1(s number, d number) return number;End;/Create or replace package body Pack_4As

Function Func_1(s number) return numberIsBeginReturn 0.1*s;End;Function Func_1(s number, d number) return number;IsBeginIf d = 1 then Return 0.2*s;ElseReturn 0.3*s;End;

End;/

Triggers (stored object) Routine or set of commands Execute automatically when some database event takes

place Written upon tables Events: BEFORE | AFTER <INSERT/UPDATE/DELETE> ON TABLE_NAME Maintain detail logs and summary logs (audit trails) for insertions/deletions/updates Stored in database in compiled format Triggers at server level [perform DML operation through any front end the trigger will

always fired] All PL/SQL statements, Exceptions are allowed in Trigger If trigger fails then DML operation also fails and vice versa for DML operation Oracle ensure data is consistent Trigger changes and DML operation changes automatically rolled back Commit and rollback not allowed within a trigger Commit and rollback have to be specified afterwards at the end of transaction then the

data will be consistent Maximum 12 trigger per table [(statement level + row level)*6 DML operation] Automatic data duplication parallel server concept in case of insert Shadow Table – in which table the data Inserted from parent table new insertion

- 39 -

Page 40: Oracle 10g PL SQL

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.sqlCreate or replace trigger Trg_1BEFORE 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.sqlCreate or replace trigger Trg_2BEFORE INSERT ON EMPFOR EACH ROW -- row level trigger fired for every rowBEGIN

Insert into output values (1, ‘Trigger started’);End;/

SQL>Ed p90.sqlCreate or replace trigger Trg_3BEFORE INSERT ON EMPFOR EACH ROWBEGINInsert into output values (:new.empno, new.ename);-- Oracle created trigger Variable access the new value-- Used: new.col_name Only in Row level triggerEnd;/

SQL>Ed p91.sqlCREATE OR REPLACE TRIGGER Trg_4BEFORE INSERT ON EMPFOR EACH ROWBEGIN: NEW.ENAME:= UPPER (:NEW.ENAME); -- data Cleansing (before insert)END;/

SQL>Ed p92.sqlCreate or replace trigger Trg_5

- 40 -

Page 41: Oracle 10g PL SQL

BEFORE INSERT ON EMPFOR EACH ROWBEGINUpdate dept set sal = sal +:new.sal where deptno =:new.deptno;End;/

SQL>Ed p93.sqlCreate or replace trigger Trg_6BEFORE delete ON EMPBEGINInsert into output values (1,’deleted’);End;/

SQL>Ed p94.sqlCreate or replace trigger Trg_7BEFORE delete ON EMP for each rowBEGINInsert into output values (:old.empno, :old.ename); -- oracle created trigger Variable access the old value-- Used: old.col_name Only in Row level triggerUpdate dept set sal = sal -:old.sal where deptno =:old.deptno;End;/

SQL>Ed p95.sqlCreate or replace trigger Trg_8BEFORE delete ON EMP for each rowBEGINInsert into output values (:old.rownum, ’row deleted’);End;/

SQL>Ed p96.sqlCreate or replace trigger Trg_9BEFORE update ON EMPBEGINInsert into output values (1, ’row updated’);End;/

SQL>Ed p97.sqlCreate or replace trigger Trg_10BEFORE update ON EMP for each rowBEGINInsert into output values (:old.empno,:old.ename);

- 41 -

Page 42: Oracle 10g PL SQL

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 backIf the end trigger is an update trigger > Error: Table is undergoing mutation

SQL>Ed p98.sqlCreate or replace trigger Trg_11BEFORE update ON EMP for each rowBEGINUpdate dept set sal = sal +:new.sal - :old.sal where deptno =:old.deptno;End;/

Procedure/function/package/trigger created with compilation errorSQL> Show errorIn Oracle two type of Table --- Relational table : using Standard Oracle datatype--- Object table : using Abstract Oracle datatype [Object Relational DBMS]Abstract Datatype (user-defined data type)

Create your user-defined structure and store in the database as an object Saves time during development Leads to standardization of structures Improves reusability Can not use constraints in Abstract Datatype Nested Abstract Datatype possible Creating Abstract datatype Oracle automatically creates some CONSTRUCTOR METHODS To insert rows into Object table use Oracle created CONSTRUCTOR METHODS Method name as per the Abstract Datatype name Can’t use specific field, to use it use sub datatype

SQL>Create or replace type addr_type as object(Street varchar2(20),City varchar2(15),State char(2),Zip number(10));/Type createdSQL>Desc addr_type

Create or replace type person_type as object(name varchar2(20),address addr_type -- using Nested Abstract Datatype);/

- 42 -

Page 43: Oracle 10g PL SQL

SQL>Create table customers(Custid number(4),Person person_type);

person_type --- name varchar2(20)--- addr_type --- Street varchar2(20),

--- City varchar2(15),--- State char(2),--- Zip number(10)

Insert into customersValues(1001, person_type(‘i-flex’, addr_type(‘MG Road’,’Bangalore’,’KN’,500055)));-- Oracle created CONSTRUCTOR METHODS

Select * from customers; -- can’t give 2D tabular formatSelect custid from customers; -- give only custidSelect person from customers; -- person column in totalSelect person.name from customers; -- wrong suppose name column from person tableSelect customers.person.name from customers; -- it worksSelect customers.person.address.city from customers; -- it works

Drop type type_name; -- can’t drop if any Table using itSelect * from user_types;Select * from all_types; TYPE_NAMESelect * from user_types;

To Raise application error: Raise_ application_error (-20001,”User defined Error”);Number range: 20001-20999

- 43 -


Recommended