Anda di halaman 1dari 75

CURSORS

Cursor is a pointer to memory location which is called as context area which contains the information necessary for processing, including the number of rows processed by the statement, a pointer to the parsed representation of the statement, and the active set which is the set of rows returned by the query.

Cursor contains two parts Header Body Header includes cursor name, any parameters and the type of data being loaded. Body includes the select statement. !" Cursor c#dno in number$ return dept%rowtype is select &from dept' (n the abo)e Header * cursor c#dno in number$ return dept%rowtype Body * select &from dept

CURSOR +,- S (mplicit #S./$ !plicit

-arameteri0ed cursors R 1 cursors CURSOR S+23 S Open 1etch Close

CURSOR 2++R(BU+ S %found %notfound %rowcount %isopen

%bul45rowcount %bul45e!ceptions CURSOR 6 C/ R2+(O7

Synta!" Cursor 8cursor_name9 is select statement' !" Cursor c is select &from dept'

CURSOR /OO-S

Simple loop :hile loop 1or loop

S(;-/

/OO-

Synta!" /oop 1etch 8cursor_name9 into 8record_variable9' !it when 8cursor_name9 % notfound' 8statements9' nd loop' !"
6 C/2R

cursor c is select & from student' )5stud student%rowtype'


B 3(7

open c' loop fetch c into )5stud' e!it when c%notfound' dbms5output.put5line#<7ame = < >> )5stud.name$' end loop' close c'

76'

Output" 7ame = sa4eth 7ame = srinu 7ame = satish 7ame = sudha

:H(/

/OO-

Synta!" :hile 8cursor_name9 % found loop 1etch 8cursor_name9 into 8record_variable9' 8statements9' nd loop' !"
6 C/2R

cursor c is select & from student' )5stud student%rowtype'


B 3(7

open c' fetch c into )5stud' while c%found loop fetch c into )5stud' dbms5output.put5line#<7ame = < >> )5stud.name$' end loop' close c'
76'

Output" 7ame = sa4eth 7ame = srinu 7ame = satish 7ame = sudha

1OR /OO-

Synta!" for 8record_variable9 in 8cursor_name9 loop 8statements9' nd loop' !"


6 C/2R

cursor c is select & from student'


B 3(7

for )5stud in c loop dbms5output.put5line#<7ame = < >> )5stud.name$' end loop' 76'

Output" 7ame = sa4eth 7ame = srinu 7ame = satish 7ame = sudha

-2R2; +2R(? 6 CURSORS

+his was used when you are going to use the cursor in more than one place with different )alues for the same where clause. Cursor parameters must be in mode. Cursor parameters may ha)e default )alues. +he scope of cursor parameter is within the select statement.

!"
6 C/2R

cursor c#dno in number$ is select & from dept where deptno = dno' )5dept dept%rowtype'
B 3(7

open c#@A$' loop fetch c into )5dept' e!it when c%notfound' dbms5output.put5line#<6name = < >> )5dept.dname >> < /oc = < >> )5dept.loc$' end loop' close c'
76'

Output" 6name =
R S 2RCH

/oc =

62//2S

-2CB23 6 CURSORS :(+H H 26 R (7 S- C 276 BO6, (7 -2CB23

BO6,

cursors declared in pac4ages will not close automatically. (n pac4aged cursors you can modify the select statement without ma4ing any changes to the cursor header in the pac4age specification. -ac4aged cursors with must be defined in the pac4age body itself, and then use it as global for the pac4age. ,ou can not define the pac4aged cursor in any subprograms. Cursor declaration in pac4age with out body needs the return clause. !"
CR 2+ OR R -/2C -2CB23 -B3 (S

cursor c return dept%rowtype is select & from dept' procedure proc is


76 -B3'

CR 2+

OR R -/2C

-2BC23

BO6, -B3 (S

cursor c return dept%rowtype is select & from dept'


-ROC 6UR B 3(7 -ROC (S

for ) in c loop dbms5output.put5line#<6eptno = < >> ).deptno >> < 6name = < >> ).dname >> < /oc = < >> ).loc$' end loop'
76 -ROC'

76 -B3'

Output"
S./9

e!ec p4g.proc 6eptno = CA 6name = 6eptno = @A 6name = 6eptno = DA 6name =


2CCOU7+(73 R S 2RCH S2/ S

/oc =

7 : ,ORB

/oc =

62//2S

/oc =

CH(C23O

6eptno = EA 6name =
CR 2+ OR R -/2C -2BC23 BO6, -B3 (S

O- R2+(O7S

/oc =

BOS+O7

cursor c return dept%rowtype is select & from dept where deptno 9 @A'
-ROC 6UR B 3(7 -ROC (S

for ) in c loop dbms5output.put5line#<6eptno = < >> ).deptno >> < 6name = < >> ).dname >> < /oc = < >> ).loc$' end loop'
76 -ROC' 76 -B3'

Output"
S./9

e!ec p4g.proc
S2/ S

6eptno = DA 6name =

/oc =

CH(C23O

6eptno = EA 6name =

O- R2+(O7S

/oc =

BOS+O7

R 1 CURSORS 276 CURSOR F2R(2B/ S

+his is unconstrained cursor which will return different types depends upon the user input. Ref cursors can not be closed implicitly. Ref cursor with return type is called strong cursor. Ref cursor with out return type is called weak cursor. ,ou can declare ref cursor type in pac4age spec as well as body. ,ou can declare ref cursor types in local subprograms or anonymous bloc4s. Cursor )ariables can be assigned from one to another. ,ou can declare a cursor )ariable in one scope and assign another cursor )ariable with different scope, then you can use the cursor )ariable e)en though the assigned cursor )ariable goes out of scope. Cursor )ariables can be passed as a parameters to the subprograms.

Cursor )ariables modes are in or out or in out. Cursor )ariables can not be declared in pac4age spec and pac4age body #e!cluding subprograms$. ,ou can not user remote procedure calls to pass cursor )ariables from one ser)er to another. Cursor )ariables can not use for update clause. ,ou can not assign nulls to cursor )ariables. ,ou can not compare cursor )ariables for equality, inequality and nullity. !"
CR 2+ OR R -/2C -ROC 6UR R 15CURSOR#+2B/ 572; (7 F2RCH2R$ (S

type t is ref cursor' c t' )5dept dept%rowtype' type r is record#ename emp.ename%type,Gob emp.Gob%type,sal emp.sal%type$' )5emp r' )5stud student.name%type'
B 3(7

if table5name =

<6 -+<

then then then

open c for select & from dept' elsif table5name = elsif table5name = end if' loop if table5name =
<6 -+< < ;-<

open c for select ename,Gob,sal from emp'


<S+U6 7+<

open c for select name from student'

then

fetch c into )5dept' e!it when c%notfound' dbms5output.put5line#<6eptno = < >> )5dept.deptno >> < 6name = < >> )5dept.dname >> < /oc = < >> )5dept.loc$'
< ;-<

elsif table5name =

then

fetch c into )5emp' e!it when c%notfound' dbms5output.put5line#< name = < >> )5emp.ename >> < Hob = < >> )5emp.Gob >> < Sal = < >> )5emp.sal$'

elsif table5name =

<S+U6 7+<

then

fetch c into )5stud' e!it when c%notfound' dbms5output.put5line#<7ame = < >> )5stud$' end if' end loop' close c'
76'

Output"

S./9

e!ec ref5cursor#<6

-+<$

6eptno = CA 6name = 6eptno = @A 6name = 6eptno = DA 6name = 6eptno = EA 6name =

2CCOU7+(73 R S 2RCH S2/ S

/oc =

7 : ,ORB

/oc =

62//2S

/oc =

CH(C23O

O- R2+(O7S

/oc =

BOS+O7

S./9

e!ec ref5cursor#<

;-<$

name = name = name = name = name = name = name = name = name = name = name = name = name = name =

S;(+H 2// 7 :2R6 HO7 S

Hob = Hob = Hob = Hob = Hob = Hob = Hob =

C/ RB

Sal = IAA Sal = CJAA Sal = C@KA Sal = @LMK Sal = C@KA Sal = @IKA Sal = @EKA Sal = KAAA Sal = CKAA

S2/ S;27 S2/ S;27 ;2723 R

;2R+(7 B/2B C/2RB SCO++ B(73

Hob =

S2/ S;27

;2723 R ;2723 R 272/,S+

Sal = DAAA

Hob =

-R S(6 7+

+UR7 R 262;S H2; S 1OR6

Hob =

S2/ S;27

Hob = Hob =

C/ RB C/ RB

Sal = CCAA Sal = LKA Sal = DAAA Sal = CDAA

Hob =

272/,S+ C/ RB

;(// R

Hob =

S./9

e!ec ref5cursor#<S+U6

7+<$

7ame = sa4eth 7ame = srinu 7ame = satish 7ame = sudha

CURSOR

N-R SS(O7S

,ou can use cursor e!pressions in e!plicit cursors. ,ou can use cursor e!pressions in dynamic S./. ,ou can use cursor e!pressions in R 1 cursor declarations and )ariables. ,ou can not use cursor e!pressions in implicit cursors. Oracle opens the nested cursor defined by a cursor e!pression implicitly as soon as it fetches the data containing the cursor e!pression from the parent or outer cursor. 7ested cursor closes if you close e!plicitly. 7ested cursor closes whene)er the outer or parent cursor is e!ecuted again or closed or canceled. 7ested cursor closes whene)er an e!ception is raised while fetching data from a parent cursor. Cursor e!pressions can not be used when declaring a )iew. Cursor e!pressions can be used as an argument to table function. ,ou can not perform bind and e!ecute operations on cursor e!pressions when using the cursor e!pressions in dynamic S./.

US(73 7 S+ 6 CURSORS OR CURSOR

N-R SS(O7S

!"
6 C/2R

cursor c is select ename,cursor#select dname from dept d where e.empno = d.deptno$ from emp e' type t is ref cursor' cC t'

c@ t' )C emp.ename%type' )@ dept.dname%type'


B 3(7

open c' loop fetch cC into )C' e!it when cC%notfound' fetch c@ into )@' e!it when c@%notfound' dbms5output.put5line#< name = < >> )C >> < 6name = < >> )@$' end loop' end loop' close c'
76'

CURSOR C/2US S

Return 1or update :here current of Bul4 collect

R +UR7

Cursor c return dept%rowtype is select &from dept' Or Cursor cC is select &from dept' Cursor c return cC%rowtype is select &from dept' Or +ype t is record#deptno dept.deptno%type, dname dept.dname%type$' Cursor c return t is select deptno, dname from dept'

1OR U-62+

276 :H R

CURR 7+ O1

7ormally, a select operation will not ta4e any loc4s on the rows being accessed. +his will allow other sessions connected to the database to change the data being selected. +he result set is still consistent. 2t open time, when the acti)e set is determined, oracle ta4es a snapshot of the table. 2ny changes that ha)e been committed prior to this point are reflected in the acti)e set. 2ny changes made after this point, e)en if they are committed, are not reflected unless the cursor is reopened, which will e)aluate the acti)e set again.

Howe)er, if the

1OR U-62+

caluse is pesent, e!clusi)e row loc4s are ta4en on the rows in

the acti)e set before the open returns. +hese loc4s pre)ent other sessions from changing the rows in the acti)e set until the transaction is committed or rolled bac4. (f another session already has loc4s on the rows in the acti)e set, then out for this waiting period. +he
S / C+ O 1OR U-62+

operation will wait for these loc4s to be released by the other session. +here is no timeP
S / C+O1OR U-62+

will hang until the other session clause is a)ailable.

releases the loc4. +o handle this situation, the

7O:2(+

Synta!" Select Ofrom O for update of column5name Qwait nR'

(f the cursor is declared with the

1OR U-62+

clause, the

:H R

CURR 7+ O1

clause can be

used in an update or delete statement.

Synta!" :here current of cursor' !"


6 C/2R

cursor c is select & from dept for update of dname'


B 3(7

for ) in c loop update dept set dname = <aa< where current of c' commit' end loop'
76

BU/B CO// C+

+his is used for array fetches :ith this you can retrie)e multiple rows of data with a single roundtrip. +his reduces the number of conte!t switches between the plSsql and sql engines. Reduces the o)erhead of retrie)ing data. ,ou can use bul4 collect in both dynamic and static sql. ,ou can use bul4 collect in select, fetch into and returning into clauses. S./ engine automatically initiali0es and e!tends the collections you reference in the bul4 collect clause. Bul4 collect operation empties the collection referenced in the into clause before e!ecuting the query. ,ou can use the limit clause of bul4 collect to restrict the no of rows retrie)ed. ,ou can fetch into multible collections with one column each. Using the returning clause we can return data to the another collection.

BU/B CO// C+ (7 1 +CH

!"
6 C/2R

+ype t is table of dept%rowtype' nt t' Cursor c is select &from dept'


B 3(7

Open c' 1etch c bul4 collect into nt' Close c' 1or i in nt.first..nt.last loop dbms5output.put5line#<6name = < >> nt#i$.dname >> < /oc = < >> nt#i$.loc$' end loop'
76'

Output" 6name = 6name = 6name =


2CCOU7+(73 R S 2RCH S2/ S

/oc =

7 : ,ORB

/oc =

62//2S

/oc =

CH(C23O

6name =

O- R2+(O7S

/oc =

BOS+O7

BU/B CO// C+ (7 S / C+

!"
6 C/2R

+ype t is table of dept%rowtype' 7t t'


B 3(7

Select & bul4 collect into nt from dept' for i in nt.first..nt.last loop dbms5output.put5line#<6name = < >> nt#i$.dname >> < /oc = < >> nt#i$.loc$' end loop'
76'

Output" 6name = 6name = 6name = 6name =


2CCOU7+(73 R S 2RCH S2/ S

/oc =

7 : ,ORB

/oc =

62//2S

/oc =

CH(C23O

O- R2+(O7S

/oc =

BOS+O7

/(;(+ (7 BU/B CO// C+

!"
6 C/2R

+ype t is table of dept%rowtype' nt t' Cursor c is select &from dept'


B 3(7

Open c' 1etch c bul4 collect into nt' Close c' 1or i in nt.first..nt.last loop dbms5output.put5line#<6name = < >> nt#i$.dname >> < /oc = < >> nt#i$.loc$' end loop'
76'

Output" 6name = 6name =


2CCOU7+(73 R S 2RCH

/oc =

7 : ,ORB

/oc =

62//2S

;U/+(-/

1 +CH S (7 (7+O C/2US

!C"
6 C/2R

+ype t is table of dept.dname%type' nt t' +ype tC is table of dept.loc%type' ntC t' Cursor c is select dname,loc from dept'
B 3(7

Open c' 1etch c bul4 collect into nt,ntC' Close c' 1or i in nt.first..nt.last loop dbms5output.put5line#<6name = < >> nt#i$$' end loop' 1or i in ntC.first..ntC.last loop dbms5output.put5line#</oc = < >> ntC#i$$' end loop'
76'

Output" 6name = 6name = 6name = 6name = /oc = /oc = /oc = /oc =


2CCOU7+(73 R S 2RCH S2/ S O- R2+(O7S

7 : ,ORB 62//2S CH(C23O BOS+O7

!@"
6 C/2R

type t is table of dept.dname%type' type tC is table of dept.loc%type' nt t' ntC tC'


B 3(7

Select dname,loc bul4 collect into nt,ntC from dept' for i in nt.first..nt.last loop dbms5output.put5line#<6name = < >> nt#i$$' end loop' for i in ntC.first..ntC.last loop dbms5output.put5line#</oc = < >> ntC#i$$' end loop'
76'

Output" 6name = 6name = 6name = 6name = /oc = /oc = /oc = /oc =


2CCOU7+(73 R S 2RCH S2/ S O- R2+(O7S

7 : ,ORB 62//2S CH(C23O BOS+O7

R +UR7(73 C/2US

(7 BU/B CO// C+

declare type t is table of number#@$' nt t "= t#C,@,D,E$' type tC is table of )archar#@$' ntC tC' type t@ is table of student%rowtype' nt@ t@'

begin select name bul4 collect into ntC from student' forall ) in ntC.first..ntC.last update student set no = nt#)$ where name = ntC#)$ returning no,name,mar4s bul4 collect into nt@' for ) in nt@.first..nt@.last loop dbms5output.put5line#<;ar4s = < >> nt@#)$$' end loop' end'

-O(7+S +O R ; ;B R

Cursor name can be up to DA characters in length. Cursors declared in anonymous bloc4s or subprograms closes automatically when that bloc4 terminates e!ecution. %bul45rowcount and %bul45e!ceptions can be used only with forall construct. Cursor declarations may ha)e e!pressions with column aliases. +hese e!pressions are called )irtual columns or calculated columns.

S./ (7 -/SS./
+he only statements allowed directly in plSsql are 6;/ and +C/.

B(76(73 Binding a )ariable is the process of identifying the storage location associated with an identifier in the program. +ypes of binding arly binding /ate binding Binding during the compiled phase is early binding. Binding during the runtime phase is late binding. (n early binding compile phase will ta4e longer because of binding wor4 but the e!ecution is faster. (n late binding it will shorten the compile phase but lengthens the e!ecution time. -lSsql by default uses early binding.

Binding also in)ol)es chec4ing the database for permissions to access the obGect Referenced.

6,72;(C S./ (f you use 66/ in plSsql it )alidates the permissions and e!istence if requires during compile time which ma4es in)alid. :e can a)oid this by using 6ynamic S./. 6ynamic S./ allows you to create a S./ statement dynamically at runtime. +wo techniques are a)ailable for 6ynamic S./. 7ati)e 6ynamic S./ 6B;S5S./ pac4age

US(73 72+(F Begin

6,72;(C S./

Using e!ecute immediate !ecute immediate Tcreate table student#no number#@$,name )archar#CA$$U' or !ecute immediate #Tcreate table student#no number#@$,name )archar#CA$$U$' nd' Using e!ecute immediate with plSsql )ariables declare ) )archar#CAA$' begin ) "= <create table student#no number#@$,name )archar#CA$$<' e!ecute immediate )' end'

Using e!ecute immediate with bind )ariables and using clause declare ) )archar#CAA$' begin ) "= <insert into student )alues#")C,")@,")D$<' e!ecute immediate ) using J,<f<,JAA' end'

!ecuting queries with open for and using clause create or replace procedure p#smar4s in number$ is s )archar#CAA$ "= <select &from student where mar4s 9 "m<' type t is ref cursor' c t' ) student%rowtype' begin open c for s using smar4s' loop fetch c into )' e!it when c%notfound' dbms5output.put5line#<Student ;ar4s = < >> ).mar4s$' end loop' close c' end' .ueries with e!ecute immediate declare d5name dept.dname%type' lc dept.loc%type' ) )archar#CAA$' begin ) "= <select dname from dept where deptno = CA<' e!ecute immediate ) into d5name' dbms5output.put5line#<6name = <>> d5name$' ) "= <select loc from dept where dname = "dn<' e!ecute immediate ) into lc using d5name' dbms5output.put5line#</oc = < >> lc$' end'

Bind )ariables 6eclare F number "= KAA' Begin Update student set mar4s = ) where' PP here ) is bind )ariable

nd'

Fariable 7ames 6eclare ;ar4s number#D$ "= CAA' Begin 6elete student where mar4s = mar4s' PP this will delete all the rows in the student table nd'

+his can be a)oided by using the labeled bloc4s. 88my5bloc499 6eclare ;ar4s number#D$ "= CAA' Begin 6elete student where mar4s = my5bloc4.mar4s' CAA nd' PP delete rows which has a mar4s of

3etting data into plSsql )ariables 6eclare FC number' F@ )archar#@$' Begin Select no,name into )C,)@ from student where mar4s = CAA' nd'

6;/ and Records create or replace procedure p#srow in student%rowtype$ is begin insert into student )alues srow' end p'

declare s student%rowtype' begin

s.no "= CC' s.name "= <aa<' s.mar4s "= CAA' p#s$' end'

Record based inserts declare srow student%rowtype' begin srow.no "= M' srow.name "= <cc<' srow.mar4s "= KAA' insert into student )alues srow' end'

Record based updates declare srow student%rowtype' begin srow.no "= J' srow.name "= <cc<' srow.mar4s "= KAA' update student set row=srow where no = srow.no' end'

Using records with returning clause declare srow student%rowtype' sreturn student%rowtype' begin srow.no "= I' srow.name "= <dd<' srow.mar4s "= KAA' insert into student )alues srow returning no,name,mar4s into sreturn'

dbms5output.put5line#<7o = < >> sreturn.no$' dbms5output.put5line#<7o = < >> sreturn.name$' dbms5output.put5line#<7o = < >> sreturn.mar4s$' end'

1orall with nonPsequential arrays declare type t is table of student.no%type inde! by binary5integer' ibt t' begin ibt#C$ "= C' ibt#CA$ "= @' forall i in ibt.first..ibt.last update student set mar4s = LAA where no = ibt#i$' end'

+he abo)e program will gi)e error li4e Telement at inde! Q@R does not e!ists.

Usage of indices of to a)oid the abo)e error declare type t is table of student.no%type inde! by binary5integer' ibt t' type tC is table of boolean inde! by binary5integer' ibtC tC' begin ibt#C$ "= C' ibt#CA$ "= @' ibt#CAA$ "= D' ibtC#C$ "= true' ibtC#CA$ "= true' ibtC#CAA$ "= true' forall i in indices of ibtC update student set mar4s = LAA where no = ibt#i$' end'

declare type t is table of student.no%type inde! by binary5integer' ibt t' type tC is table of pls5integer inde! by binary5integer' ibtC tC' begin ibt#C$ "= C' ibt#CA$ "= @' ibt#CAA$ "= D' ibtC#CC$ "= C' ibtC#CK$ "= CA' ibtC#CI$ "= CAA' forall i in )alues of ibtC update student set mar4s = KJM where no = ibt#i$' end'

Bul4 Binds -assing the entire plSsql table to the S./ engine in one step is 4nown as bul4 bind. Bul4 binds are done using the forall statement. (f there is an error processing one of the rows in bul4 6;/ operation, only that row is rolled bac4. Returning clause +his will be used only with 6;/ statements to return data into plSsql )ariables. +his will be useful in situations li4e , when performing insert or update or delete if you want to 4now the data of the table which has been effected by the 6;/. :ith out going for another S / C+ using R +UR7(73 clause we will get the data which will a)oid a call to R6B;S 4erne

RROR H276/(73
-/SS./ implements error handling with e!ceptions and e!ception handlers. !ceptions

can be associated with oracle errors or with your own userPdefined errors. By using

e!ceptions and e!ception handlers, you can ma4e your -/SS./ programs robust and able to deal with both une!pected and e!pected errors during e!ecution.

RROR +,- S

CompilePtime errors Runtime errors

rrors that occur during the compilation phase are detected by the -/SS./ engine and reported bac4 to the user, we ha)e to correct them. Runtime errors are detected by the -/SS./ runtime engine which can programmatically raise and caught by e!ception handlers. !ceptions are designed for runPtime error handling, rather than compilePtime error handling.

H276/(73

NC -+(O7S

:hen e!ception is raised, control passes to the e!ception section of the bloc4. +he e!ception section consists of handlers for some or all of the e!ceptions. 2n e!ception handler contains the code that is e!ecuted when the error associated with the e!ception occurs, and the e!ception is raised.

Synta!"
NC -+(O7

:hen e!ception5name then Sequence5of5statements' :hen e!ception5name then Sequence5of5statements' :hen others then Sequence5of5statements'
76'

NC -+(O7 +,- S

-redefined e!ceptions UserPdefined e!ceptions

-R 6 1(7 6

NC -+(O7S

Oracle has predefined se)eral e!ceptions that corresponds to the most common oracle errors. /i4e the predefined types, the identifiers of these e!ceptions are defined in the
S+2762R6

pac4age. Because of this, they are already a)ailable to the program, it is not

necessary to declare them in the declarati)e secion.

!C"
6 C/2R

a number' b )archar#@$' )5mar4s number' cursor c is select & from student' type t is )array#D$ of )archar#@$' )a t "= t#<a<,<b<$' )aC t'
B 3(7 PP 7O562+251OU76 B 3(7

select smar4s into )5mar4s from student where sno = KA'


NC -+(O7

when no5data5found then dbms5output.put5line#<(n)alid student number<$'


76' PP CURSOR52/R 26,5O- 7 B 3(7

open c' open c'


NC -+(O7

when cursor5already5open then dbms5output.put5line#<Cursor is already opened<$'


76'

PP (7F2/(65CURSOR

B 3(7

close c' open c' close c' close c'


NC -+(O7

when in)alid5cursor then dbms5output.put5line#<Cursor is already closed<$'


76' PP +OO5;27,5RO:S B 3(7

select smar4s into )5mar4s from student where sno 9 C'


NC -+(O7

when too5many5rows then dbms5output.put5line#<+oo many )alues are coming to mar4s )ariable<$'
76' PP ? RO56(F(6 B 3(7

a "= KSA'
NC -+(O7

when 0ero5di)ide then dbms5output.put5line#<6i)ided by 0ero P in)alid operation<$'


76' PP F2/U 5 RROR B 3(7

b "= <sa4eth<'
NC -+(O7

when )alue5error then dbms5output.put5line#<(n)alid string length<$'


76' PP (7F2/(657U;B R B 3(7

insert into student )alues#<a<,<srinu<,CAA$'


NC -+(O7

when in)alid5number then dbms5output.put5line#<(n)alid number<$'


76' PP SUBSCR(-+5OU+S(6 5/(;(+ B 3(7

)a#E$ "= <c<'


NC -+(O7

when subscript5outside5limit then dbms5output.put5line#<(nde! is greater than the limit<$'


76' PP SUBSCR(-+5B ,O765COU7+ B 3(7

)a#D$ "= <c<'


NC -+(O7

when subscript5beyond5count then dbms5output.put5line#<(nde! is greater than the count<$'


76' PP CO// C+(O75(S57U// B 3(7

)aC#C$ "= <a<'


NC -+(O7

when collection5is5null then dbms5output.put5line#<Collection is empty<$'


76'

PP
76'

Output" (n)alid student number Cursor is already opened Cursor is already closed +oo many )alues are coming to mar4s )ariable 6i)ided by 0ero P in)alid operation (n)alid string length (n)alid number (nde! is greater than the limit (nde! is greater than the count Collection is empty

!@"
6 C/2R

c number'

B 3(7

c "= KSA'
NC -+(O7

when 0ero5di)ide then dbms5output.put5line#<(n)alid Operation<$' when others then dbms5output.put5line#<1rom O+H RS handler" (n)alid Operation<$'
76'

Output" (n)alid Operation

US RP6 1(7 6

NC -+(O7S

2 userPdefined e!ception is an error that is defined by the programmer. UserPdefined e!ceptions are declared in the declarati)e secion of a -/SS./ bloc4. Hust li4e )ariables, e!eptions ha)e a type
NC -+(O7

and scope.

R2(S(73

NC -+(O7S

UserPdefined e!ceptions are raised e!plicitly )ia the R2(S !"


6 C/2R

statement.

e e!ception'
B 3(7

raise e'
NC -+(O7

when e then dbms5output.put5line#<e is raised<$'


76'

Output" e is raised

BU/(+P(7

RROR 1U7C+(O7S

S./CO6

276 S./ RR;

S./CO6

returns the current error code, and

S./ RR;

returns the current error message returns VuserPdeifned

te!t' 1or userPdefined e!ception e!ceptionW. S./ RR; wiil ta4e only negati)e )alue e!cept CAA. (f any positi)e )alue other than CAA returns nonPoracle e!ception. !C"
6 C/2R S./CO6

returns C and

S./ RR;

e e!ception' )5dname )archar#CA$'


B 3(7 PP US RP6 1(7 6 B 3(7 NC -+(O7

raise e'
NC -+(O7

when e then dbms5output.put5line#S./CO6 >> < < >>


76' S./ RR;$'

PP -R 6 1(7 6 B 3(7

NC -+(O7

select dname into )5dname from dept where deptno = KA'


NC -+(O7

when no5data5found then dbms5output.put5line#S./CO6 >> < < >>


76' 76' S./ RR;$'

Output" C UserP6efined !ception CAA OR2PACEAD" no data found

!@"
B 3(7

dbms5output.put5line#S./ dbms5output.put5line#S./

RR;#CAA$$' RR;#A$$'

dbms5output.put5line#S./ dbms5output.put5line#S./ dbms5output.put5line#S./ dbms5output.put5line#S./ dbms5output.put5line#S./


76'

RR;#C$$' RR;#PCAA$$' RR;#PKAA$$' RR;#@AA$$' RR;#PLAA$$'

Output" OR2PACEAD" no data found OR2PAAAA" normal, successful completion UserP6efined !ception OR2PAACAA" no data found OR2PAAKAA" ;essage KAA not found' product=R6B;S' facility=OR2 P@AA" nonPOR2C/ e!ception OR2PAALAA" in)alid S./ statement

6B;S5U+(/(+,.1OR;2+5 RROR5S+2CB

+he builtPin function, li4e error. (t differs from


S./ RR;

S./ RR;,

returns the message associated with the current

in two ways"

(ts length is not restricted' it will return the full error message string. ,ou can not pass an error code number to this function' it cannot be used to return the message for a random error code. !"
6 C/2R

) number "= <ab<'


B 3(7

null'
NC -+(O7

when others then dbms5output.put5line#dbms5utility.format5error5stac4$'


76'

Output" declare & RROR at line C"

OR2PAJKA@" -/SS./" numeric or )alue error" character to number con)ersion error OR2PAJKC@" at line @

6B;S5U+(/(+,.1OR;2+5C2//5S+2CB

+his function returns a formatted string showing the e!ecution call stac4 inside your
-/SS./

application. (ts usefulness is not restricted to error management' you will also

find its handy for tracing the e!ectution of your code. ,ou may not use this function in e!ception bloc4. !"
B 3(7

dbms5output.put5line#dbms5utility.format5call5stac4$'
76'

Output" PPPPP -/SS./ Call Stac4 PPPPP ObGect5handle JLMJAEMI line5number obGect5name @ anonymous bloc4

6B;S5U+(/(+,.1OR;2+5 RROR5B2CB+R2C

(t displays the e!ecution stac4 at the point where an e!ception was raised. +hus , you can call this function with an e!ception section at the top le)el of your stac4 and still find out where the error was raised deep within the call stac4. !"
CR 2+ B 3(7 OR R -/2C -ROC 6UR -C (S

dbms5output.put5line#<from procedure C<$' raise )alue5error'


76 -C'

CR 2+ B 3(7

OR R -/2C

-ROC 6UR

-@ (S

dbms5output.put5line#<from procedure @<$' pC'


76 -@'

CR 2+ B 3(7

OR R -/2C

-ROC 6UR

-D (S

dbms5output.put5line#<from procedure D<$' p@'


NC -+(O7

when others then dbms5output.put5line#dbms5utility.format5error5bac4trace$'


76 -D'

Output"
S./9

e!ec pD

from procedure D from procedure @ from procedure C OR2PAJKC@" at XS2B +H.-CX, line E OR2PAJKC@" at XS2B +H.-@X, line E OR2PAJKC@" at XS2B +H.-DX, line E

NC -+(O75(7(+ -R23;2

Using this you can associate a named e!ception with a particular oracle error. +his gi)es you the ability to trap this error specifically, rather than )ia an Synta!"
-R23;2 NC -+(O75(7(+#exception_name, O+H RS

handler.

oracle_error_number$'

!"
6 C/2R

e e!ception' pragma e!ception5init#e,PCEMJ$' c number'


B 3(7

c "= KSA'
NC -+(O7

when e then dbms5output.put5line#<(n)alid Operation<$'


76'

Output" (n)alid Operation

R2(S 52--/(C2+(O75 RROR

,ou can use this builtPin function to create your own error messages, which can be more descripti)e than named e!ceptions. Synta!"
R2(S 52--/(C2+(O75 RROR#error_number,

error_message,, Qkeep_errors_flagR$'
+RU

+he Boolean parameter keep_errors_flag is optional. (f it is to the list of errors already raised. (f it is replace the current list of errors. !"
6 C/2R 12/S

, the new error is added

, which is default, the new error will

c number'
B 3(7

c "= KSA'

NC -+(O7

when 0ero5di)ide then raise5application5error#P@A@@@,<(n)alid Operation<$'


76'

Output"
6 C/2R

&
RROR

at line C"

OR2P@A@@@" (n)alid Operation OR2PAJKC@" at line M

NC -+(O7 -RO-232+(O7

!ceptions can occur in the declarati)e, the e!ecutable, or the e!ception section of a -/SS./ bloc4.

NC -+(O7 R2(S 6 (7 +H

N CU2+2B/

S C+(O7

!ceptions raised in e!ecuatable section can be handled in current bloc4 or outer bloc4. !C"
6 C/2R

e e!ception'
B 3(7 B 3(7

raise e'
76' NC -+(O7

when e then dbms5output.put5line#<e is raised<$'


76'

Output" e is raised

!@"
6 C/2R

e e!ception'
B 3(7 B 3(7

raise e'
76' 76'

Output"
RROR

at line C"

OR2PAJKCA" -/SS./" unhandled userPdefined e!ception OR2PAJKC@" at line K

NC -+(O7 R2(S 6 (7 +H

6 C/2R2+(F

S C+(O7

!ceptions raised in the declarati)e secion must be handled in the outer bloc4. !C"
6 C/2R

c number#D$ "= <abcd<'


B 3(7

dbms5output.put5line#<Hello<$'
NC -+(O7

when others then dbms5output.put5line#<(n)alid string length<$'


76'

Output"
RROR

at line C"

OR2PAJKA@" -/SS./" numeric or )alue error" character to number con)ersion error OR2PAJKC@" at line @

!@"
B 3(7 6 C/2R

c number#D$ "= <abcd<'


B 3(7

dbms5output.put5line#<Hello<$'
NC -+(O7

when others then dbms5output.put5line#<(n)alid string length<$'


76' NC -+(O7

when others then dbms5output.put5line#<1rom outer bloc4" (n)alid string length<$'


76'

Output" 1rom outer bloc4" (n)alid string length

NC -+(O7 R2(S 6 (7 +H

NC -+(O7 S C+(O7

!ceptions raised in the declarati)e secion must be handled in the outer bloc4. !C"
6 C/2R

eC e!ception' e@ e!ception'
B 3(7

raise eC'
NC -+(O7

when eC then dbms5output.put5line#<eC is raised<$' raise e@' when e@ then dbms5output.put5line#<e@ is raised<$'
76'

Output" eC is raised 6 C/2R & RROR at line C" OR2PAJKCA" -/SS./" unhandled userPdefined e!ception OR2PAJKC@" at line L OR2PAJKCA" -/SS./" unhandled userPdefined e!ception

!@"
6 C/2R

eC e!ception' e@ e!ception'
B 3(7 B 3(7

raise eC'
NC -+(O7

when eC then dbms5output.put5line#<eC is raised<$' raise e@' when e@ then dbms5output.put5line#<e@ is raised<$'
76' NC -+(O7

when e@ then dbms5output.put5line#<1rom outer bloc4" e@ is raised<$'


76'

Output"

eC is raised 1rom outer bloc4" e@ is raised

!D"
6 C/2R

e e!ception'
B 3(7

raise e'
NC -+(O7

when e then dbms5output.put5line#<e is raised<$' raise e'


76'

Output" e is raised 6 C/2R & RROR at line C" OR2PAJKCA" -/SS./" unhandled userPdefined e!ception OR2PAJKC@" at line I OR2PAJKCA" -/SS./" unhandled userPdefined e!ception

R S+R(C+(O7S

,ou can not pass e!ception as an argument to a subprogram

62+2B2S

+R(33 RS

+riggers are similar to procedures or functions in that they are named -/SS./ bloc4s with declarati)e, e!ecutable, and e!ception handling sections. 2 trigger is e!ecuted implicitly whene)er the triggering e)ent happens. +he act of e!ecuting a trigger is 4nown as firing the trigger. R S+R(C+(O7S O7 +R(33 R S

/i4e pac4ages, triggers must be stored as standPalone obGects in the database and cannot be local to a bloc4 or pac4age. 2 trigger does not accept arguments. US O1 +R(33 RS

;aintaining comple! integrity constraints not possible through declarati)e constraints enable at table creation. 2uditing information in a table by recording the changes made and who made them. 2utomatically signaling other programs that action needs to ta4e place when chages are made to a table. -erform )alidation on changes being made to tables. 2utomate maintenance of the database. +,- S O1 +R(33 RS 6;/ +riggers (nstead of +riggers 66/ +riggers System +riggers Suspend +riggers C2+ 3OR( S +iming /e)el PP PP Before or 2fter Row or Statement 2CH RO: clause.

Row le)el trigger fires once for each row affected by the triggering statement. Row le)el trigger is identified by the 1OR Statement le)el trigger fires once either before or after the statement. 6;/ +R(33 R S,7+2N Create or replace trigger 8trigger_name9 Before > after on insert or update or delete Q1or each rowR

Begin PP trigger body nd 8trigger_name9' 6;/ +R(33 RS 2 6;/ trigger is fired on an (7S R+, U-62+ , or 6 / + affected row, or once per statement. +he combination of these factors determines the types of the triggers. +hese are a total of C@ possible types #D statements & @ timing & @ le)els$. OR6 R O1 6;/ +R(33 R 1(R(73 Before statement le)el Before row le)el 2fter row le)el 2fter statement le)el !" Suppose we ha)e a follwing table. S./9 select & from student' 7O 72; C @ D E a b c d ;2RBS CAA @AA DAA EAA operation on a database table.

(t can be fired either before or after the statement e!ecutes, and can be fired once per

PPPPP PPPPPPP PPPPPPPPPP

2lso we ha)e triggering5firing5order table with firing5order as the field. CR 2+ B 3(7 OR R -/2C +R(33 R +R(33 RC

before insert on student

insert into trigger5firing5order )alues#<Before Statement /e)el<$' 76 +R(33 RC' CR 2+ OR R -/2C +R(33 R +R(33 R@

before insert on student for each row B 3(7 insert into trigger5firing5order )alues#<Before Row /e)el<$' 76 +R(33 R@' CR 2+ B 3(7 insert into trigger5firing5order )alues#<2fter Statement /e)el<$' 76 +R(33 RD' CR 2+ OR R -/2C +R(33 R +R(33 RE OR R -/2C +R(33 R +R(33 RD

after insert on student

after insert on student for each row B 3(7 insert into trigger5firing5order )alues#<2fter Row /e)el<$' 76 +R(33 RE' Output" S./9 select & from trigger5firing5order' no rows selected S./9 insert into student )alues#K,<e<,KAA$' C row created. S./9 select & from trigger5firing5order' 1(R(735OR6 R

PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP Before Statement /e)el Before Row /e)el 2fter Row /e)el 2fter Statement /e)el S./9 select & from student' 7O 72; C @ D E K a b c d e ;2RBS CAA @AA DAA EAA KAA

PPPP PPPPPPPP PPPPPPPPPP

CORR /2+(O7 (6 7+(1( RS (7 RO:P/ F / +R(33 RS (nside the trigger, you can access the data in the row that is currently being processed. +his is accomplished through two correlation identifiers P "old and "new. 2 correlation identifier is a special 4ind of -/SS./ bind )ariable. +he colon in front of each indicates that they are bind )ariables, in the sense of host )ariables used in embedded -/SS./, and indicates that they are not regular -/SS./ )ariables. +he -/SS./ compiler will treat them as records of type +riggering5table%RO:+,- . 2lthough syntactically they are treated as records, in reality they are not. "old and "new are also 4nown as pseudorecords, for this reason. +R(33 R(73 S+2+ ; 7+ PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP (7S R+ inserted :hen the statement is completed. "O/6 PPPPPPPPPPPPPPPPPPPPPPPPPPPP all fields are 7U//. )alues that will be "7 :

PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

U-62+ updated

original )alues for the row before the update.

new )alues that will be when the statement is completed. all fields are 7U//.

6 / +

original )alues before the row is deleted.

!" Suppose we ha)e a table called mar4s with fields no, old5mar4s, new5mar4s. CR 2+ OR R -/2C +R(33 R O/657 :

before insert or update or delete on student for each row B 3(7 insert into mar4s )alues#"old.no,"old.mar4s,"new.mar4s$' 76 O/657 :' Output" S./9 select & from student' 7O 72; C @ D E K a b c d e ;2RBS CAA @AA DAA EAA KAA

PPPPP PPPPPPP PPPPPPPPPP

S./9 select & from mar4s' no rows selected S./9 insert into student )alues#J,<f<,JAA$'

C row created. S./9 select & from student' 7O 72; C @ D E K J a b c d e f ;2RBS CAA @AA DAA EAA KAA JAA

PPPP PPPPPPPP PPPPPPPPPP

S./9 select & from mar4s' 7O O/65;2RBS 7 :5;2RBS PPPP PPPPPPPPPPPPPPP PPPPPPPPPPPPPPP JAA S./9 update student set mar4s=KKK where no=K' C row updated. S./9 select & from student' 7O 72; C @ D E K J a b c d e f ;2RBS CAA @AA DAA EAA KKK JAA

PPPPP PPPPPPP PPPPPPPPPP

S./9 select & from mar4s'

7O

O/65;2RBS

7 :5;2RBS JAA

PPPPPP PPPPPPPPPPPPPPPP PPPPPPPPPPPPPPP K KAA KKK

S./9 delete student where no = @' C row deleted. S./9 select & from student' 7O 72; C D E K J a c d e f ;2RBS CAA DAA EAA KKK JAA

PPPP PPPPPPPP PPPPPPPPPP

S./9 select & from mar4s' 7O O/65;2RBS 7 :5;2RBS PPPPP PPPPPPPPPPPPPP PPPPPPPPPPPPPPPP JAA K @ KAA @AA KKK

R 1 R 7C(73 C/2US (f desired, you can use the R 1 R 7C(73 clause to specify a different name for "old ane "new. +his clause is found after the triggering e)ent, before the :H 7 clause. Synta!" R 1 R 7C(73 Qold as old5nameR Qnew as new5nameR !" CR 2+ OR R -/2C +R(33 R R 1 R 7C 5+R(33 R

before insert or update or delete on student referencing old as old5student new as new5student for each row B 3(7 insert into mar4s )alues#"old5student.no,"old5student.mar4s,"new5student.mar4s$' 76 R 1 R 7C 5+R(33 R' :H 7 C/2US :H 7 clause is )alid for rowPle)el triggers only. (f present, the trigger body will be e!ecuted only for those rows that meet the condition specified by the :H 7 clause. Synta!" :H 7 trigger_condition' :here trigger_condition is a Boolean e!pression. (t will be e)aluated for each row. +he :new and :old records can be referenced inside trigger_condition as well, but li4e R 1 R 7C(73, the colon is not used there. +he colon is only )alid in the trigger body. !" CR 2+ OR R -/2C +R(33 R :H 75+R(33 R before insert or update or delete on student referencing old as old5student new as new5student for each row when #new5student.mar4s 9 KAA$ B 3(7 insert into mar4s )alues#"old5student.no,"old5student.mar4s,"new5student.mar4s$' 76 :H 75+R(33 R' +R(33 R -R 6(C2+ S +here are three Boolean functions that you can use to determine what the operation is. +he predicates are

(7S R+(73 U-62+(73 6 / +(73

!" CR 2+ B 3(7 if inserting then insert into predicates )alues#<(<$' elsif updating then insert into predicates )alues#<U<$' elsif deleting then insert into predicates )alues#<6<$' end if' 76 -R 6(C2+ 5+R(33 R' Output" S./9 delete student where no=C' C row deleted. S./9 select & from predicates' ;S3 PPPPPPPPPPPPPPP 6 S./9 insert into student )alues#M,<g<,MAA$' C row created. S./9 select & from predicates' OR R -/2C +R(33 R -R 6(C2+ 5+R(33 R

before insert or update or delete on student

;S3 PPPPPPPPPPPPPPP 6 ( S./9 update student set mar4s = MMM where no=M' C row updated. S./9 select & from predicates'

;S3 PPPPPPPPPPPPPPP 6 ( U (7S+ 26PO1 +R(33 RS (nsteadPof triggers fire instead of a 6;/ operation. 2lso, insteadPof triggers can be defined only on )iews. (nsteadPof triggers are used in two cases" +o allow a )iew that would otherwise not be modifiable to be modified. +o modify the columns of a nested table column in a )iew.

S,S+ ; +R(33 RS System triggers will fire whene)er databasePwide e)ent occurs. +he following are the database e)ent triggers. +o create system trigger you need 26;(7(S+ R 62+2B2S +R(33 R pri)ilege. S+2R+U SHU+6O:7

/O3O7 /O3O11 S RF R RROR Synta!" Create or replace trigger 8trigger_name9 YBefore > afterZ Y6atabase e)entZ on Ydatabase > schemaZ Q:hen #O$R Q6eclareR PP declaration section Begin PP trigger body Q !ceptionR PP e!ception section nd 8trigger_name9' !" S./9 create table user5logs#u5name )archar#CA$,log5time timestamp$' CR 2+ B 3(7 insert into user5logs )alues#user,current5timestamp$' 76 21+ R5/O3O7' Output" S./9 select & from user5logs' no rows selected S./9 conn sa4ethSsa4eth S./9 select & from user5logs' OR R -/2C +R(33 R 21+ R5/O3O7

after logon on database

U572; S2B +H

/O35+(; @@PHU/PAM C@.AM.CD.CEAAAA 2;

PPPPPPPPPP PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

S./9 conn systemSoracle S./9 select & from user5logs'

U572; S2B +H S,S+ ;

/O35+(; @@PHU/PAM C@.AM.CD.CEAAAA 2; @@PHU/PAM C@.AM.DE.@CIAAA 2;

PPPPPPPPPP PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

S./9 conn scottStiger S./9 select & from user5logs' U572; S2B +H S,S+ ; SCO++ /O35+(; @@PHU/PAM C@.AM.CD.CEAAAA 2; @@PHU/PAM C@.AM.DE.@CIAAA 2; @@PHU/PAM C@.AI.ED.ALDAAA 2;

PPPPPPPPPP PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP

S RF R RROR +he S RF R RROR e)ent can be used to trac4 errors that occur in the database. +he error code is a)ailable inside the trigger through the S RF R5 RROR attribute function. !" S./9 create table my5errors#error5msg )archar#@AA$$' CR 2+ B 3(7 insert into my5errors )alues#dbms5utility.format5error5stac4$' 76 S RF R5 RROR5+R(33 R' OR R -/2C +R(33 R S RF R5 RROR5+R(33 R

after ser)ererror on database

Output" S./9 create table ss #no$$' create table ss #no$$ & RROR at line C" OR2PAAL@@" missing or in)alid option S./9 select & from my5errors' RROR5;S3 PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP OR2PAAL@@" missing or in)alid option S./9 insert into student )alues#C,@,D$' insert into student )alues#C,@,D$ & RROR at line C" OR2PAALE@" table or )iew does not e!ist S./9 select & from my5errors' RROR5;S3 PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP OR2PAAL@@" missing or in)alid option OR2PAALE@" table or )iew does not e!ist S RF R5 RROR 2++R(BU+ 1U7C+(O7

(t ta4es a single number type of argument and returns the error at the position on the error stac4 indicated by the argument. +he position C is the top of the stac4. !" CR 2+ OR R -/2C +R(33 R S RF R5 RROR5+R(33 R

after ser)ererror on database

B 3(7 insert into my5errors )alues#ser)er5error#C$$' 76 S RF R5 RROR5+R(33 R' SUS- 76 +R(33 RS +his will fire whene)er a statement is suspended. +his might occur as the result of a space issue such as e!ceeding an allocated tablepace quota. +his functionality can be used to address the problem and allow the operatin to continue.

Synta!" Create or replace trigger 8trigger_name9 after suspend on Ydatabase > schemaZ Q:hen #O$R Q6eclareR PP declaration section Begin PP trigger body Q !ceptionR PP e!ception section nd 8trigger_name9' !" S./9 create tablespace my5space datafile <f"[my5file.dbf< si0e @m' S./9 create table student#sno number#@$,sname )archar#CA$$ tablespace my5space' CR 2+ B 3(7 dbms5output.put5line#T 7o room to insert in your tablespace<$' 76 SUS- 765+R(33 R' Output" OR R -/2C +R(33 R SUS- 765+R(33 R

after suspend on database

(nsert more rows in student table then , you will get 7o room to insert in your tablespace

-ROC 6UR S

2 procedure is a module that performs one or more actions. Synta!" -rocedure Qschema.Rname Q#parameter1 Q,parameter2 OR$R Qauthid definer > current5userR is PP QdeclarationsR Begin PP e!ecutable statements Q !ception PP e!ception handlersR nd QnameR' (n the abo)e authid clause defines whether the procedure will e!ecute under the authority of the definer of the procedure or under the authority of the current user.

1U7C+(O7S

2 function is a module that returns a )alue. Synta!" 1unction Qschema.Rname Q#parameter1 Q,parameter2 OR$R Return return5datatype Qauthid definer > current5userR QdeterministicR Qparallel5enableR is PP QdeclarationsR Begin PP e!ecutable statements Q !ception PP e!ception handlersR nd QnameR' (n the abo)e authid clause defines whether the procedure will e!ecute under the authority of the definer of the procedure or under the authority of the current user.

Deterministic clause defines, an optimi0ation hint that lets the system use a sa)ed copy of the functionUs return result, if a)ailable. +he quety optimi0er can choose whether to use the sa)ed copy or rePcall the function. Parallel_enable clause defines, an optimi0ation hint that enables the function to be e!ecuted in parallel when called from within S / C+ statement.

-2R2; + R ;O6 S (n #6efault$ Out (n out


(7

(n parameter will act as pl/s l constant.


OU+

Out parameter will act as unintiali!ed variable. ,ou cannot pro)ide a default )alue to an out parameter. 2ny assignments made to out parameter are rolled bac4 when an e!ception is raised in the program. 2n actual parameter corresponding to an out formal parameter must be a )ariable.
(7 OU+

(n out parameter will act as initiali!ed variable. 2n actual parameter corresponding to an in out formal parameter must be a )ariable.

6 12U/+ -2R2; + RS 6efault -arameters will not allow in the beginning and middle. "ut and #n "ut parameters can not ha)e default )alues. !" procedure procedure procedure procedure procedure procedure

p#a p#a p#a p#a p#a p#a

in in in in in in

number default K, b in number default J, c in number default M$ * )alid number, b in number default J, c in number default M$ * )alild number, b in number, c in number default M$ * )alild number, b in number default J, c in number$ * in)alild number default K, b in number default J, c in number$ * in)alild number default K, b in number, c in number$ * in)alild

7O+2+(O7S

7otations are of two types. -ositional notation 7ame notation :e can combine positional and name notation but positional notation can not be followed by the name notation. !"

Suppose we ha)e a procedure proc#a number,b number,c number$ and we ha)e one anonymous bloc4 which contains )C,)@, and )D' e!ec proc #)C,)@,)D$ e!ec proc #a=9)C,b=9)@,c=9)D$ PP -ositional notation PP 7amed notation

S./9 S./9

1OR;2/ 276 2C+U2/ -2R2; + RS -arametes which are in calling subprogram are actual parameters. -arametes which are in called subprogram are formal parameters. (f any subprogram was called, once the call was completed then the )alues of formal parameters are copied to the actual parameters. !C"
CR 2+ B 3(7 OR R -/2C -ROC 6UR S2;-/

#a in number,b out number,c in out number$ is

76 S2;-/ ' 6 C/2R

dbms5output.put5line#<2fter call<$' dbms5output.put5line#<a = < >> a >>< b = < >> b >> < c = < >> c$' b "= CA' c "= @A' dbms5output.put5line#<2fter assignment<$' dbms5output.put5line#<a = < >> a >>< b = < >> b >> < c = < >> c$'

B 3(7

)C number "= E' )@ number "= K' )D number "= J' dbms5output.put5line#<Before call<$' dbms5output.put5line#<)C = < >> )C >> < )@ = < >> )@ >> < )D = < >> )D$' sample#)C,)@,)D$' dbms5output.put5line#<2fter completion of call<$' dbms5output.put5line#<)C = < >> )C >> < )@ = < >> )@ >> < )D = < >> )D$'

76'

Output" Before call )C = E )@ = K )D = J 2fter call a=Eb= c=J 2fter assignment

a = E b = CA c = @A 2fter completion of call )C = E )@ = CA )D = @A !@" CR 2+ OR R -/2C 1U7#a in number,b out number,c in out number$ return number (S
B 3(7

76 1U7' 6 C/2R

dbms5output.put5line#<2fter call<$' dbms5output.put5line#<a = < >> a >> < b = < >> b >> < c = < >> c$' dbms5output.put5line#<Before assignement Result = < >> #a&n)l#b,C$&c$$' b "= K' c "= M' dbms5output.put5line#<2fter assignment<$' dbms5output.put5line#<a = < >> a >> < b = < >> b >> < c = < >> c$' return #a&b&c$'

)C number "= C' )@ number "= @' )D number "= D' ) number'
B 3(7

76'

dbms5output.put5line#<Before call<$' dbms5output.put5line#<)C = < >> )C >> < )@ = < >> )@ >> < )D = < >> )D$' ) "= fun#)C,)@,)D$' dbms5output.put5line#<2fter call completed<$' dbms5output.put5line#<)C = < >> )C >> < )@ = < >> )@ >> < )D = < >> )D$' dbms5output.put5line#<Result = < >> )$'

Output" Before call )C = C )@ = @ )D = D 2fter call a=Cb= c=D Before assignement Result = D 2fter assignment a=Cb=Kc=M 2fter call completed )C = C )@ = K )D = M Result = DK
R S+R(C+(O7S O7 1OR;2/ -2R2; + RS

By declaring with specified si0e in actual parameters. By declaring formal parameters with %type specifier. US(73 7OCO-, $ocop% is a hint, not a command. +his means that the compiler might silently decide that it canUt fulfill your request for a nocop% parameter. +he copying from formal to actual can be restricted by issuing nocop% qualifier.

+o pass the out and in out parameters by reference use nocopy qualifier. !"
CR 2+ OR R -/2C B 3(7 PPPP 76 -ROC' -ROC 6UR -ROC#a

in out nocopy number$ (S

C2// 276 Call is a


S./

N C statement, which can be used to e!ecute subprograms li4e e!ec.

Synta!" Call subprogram_name#Qargument_listR$ Qinto host_variableR' +he parantheses are always required, e)en if the subprogram ta4es no arguments. :e can not use call with out and in out parameters. Call is a S./ statement, it is not )alid inside a -/SS./ bloc4' +he (7+O clause is used for the output )ariables of functions only. :e can not use Te!ecU with out or in out parameters. !ec is not )alid inside a -/SS./ bloc4'

CR 2+ B 3(7

!C"

OR R -/2C

-ROC (S

dbms5output.put5line#<hello world<$'

76 -ROC'

Output" S./9 call proc#$' hello world !@"


CR 2+ B 3(7 OR R -/2C

-ROC#a

in number,b in number$

(S

dbms5output.put5line#<a = < >> a >> < b = < >> b$'

76 -ROC'

Output" S./9 call proc#K,J$' a=Kb=J !D"

CR 2+ B 3(7

OR R -/2C

1U7C+(O7 1U7 R +UR7 F2RCH2R (S

return <hello world<'

76 1U7'

Output" S./9 )ariable ) )archar#@A$ S./9 call fun#$ into ")' S./9 print )

hello world C2// B, R 1 R 7C 276 C2// B, F2/U

(n parameters by default call b% reference where as out and in out call b% value. :hen parameter passed by reference, a pointer to the actual parameter is passed to the corresponding formal parameter. :hen parameter passed by )alue it copies the )alue of the actual parameter to the formal parameter. Call by reference is faster than the call by )alue because it a)oids the copying. SUB-RO3R2;S OF R/O26(73 -ossible with different number of parameters. -ossible with different types of data. -ossible with same type with obGects. Can not be possible with different types of modes. :e can o)erload local subprograms also. !"
S./9 S./9 6 C/2R

create or replace type tC as obGect#a number$'S create or replace type tC as obGect#a number$'S

-ROC 6UR B 3(7 76 -' -ROC 6UR B 3(7 76 -' -ROC 6UR B 3(7

i tC "= tC#K$' G t@ "= t@#K$'

-#m tC$ (S

dbms5output.put5line#<a = < >> m.a$'


-#n t@$ (S

dbms5output.put5line#<b = < >> n.b$'


-RO6UC+#a number,b number$ (S

dbms5output.put5line#<-roduct of a,b = < >> a & b$'

76 -RO6UC+' -ROC 6UR -RO6UC+#a number,b number,c number$ (S B 3(7 76 -RO6UC+' B 3(7

dbms5output.put5line#<-roduct of a,b = < >> a & b & c$'

p#i$' p#G$' product#E,K$' product#E,K,J$'


76'

Output" a=K b=K -roduct of a,b = @A -roduct of a,b = C@A

B 7 1(+S O1 OF R/O26(73

Supporting many data combinations 1itting the program to the user.


R S+R(C+(O7S O7 OF R/O26(73

O)erloaded programs with parameter lists that differ only by name must be called using named notation. +he parameter list of o)erloaded programs must differ by more than parameter mode. 2ll of the o)erloaded programs must be defined within the same -/SS./ scope or bloc4. O)erloaded functions must differ by more than their return type.

(;-OR+27+ -O(7+S 2BOU+ SUB-RO3R2;S :hen a stored subprogram is created, it is stored in the data dictionar%. +he subprogram is stored in compile form which is 4nown as p&code in addition to the source te!t. +he pPcode has all of the references in the subprogram e)aluated, and the source code is translated into a form that is easily readable by -/SS./ engine. :hen the subprogram is called, the pPcode is read from the dis4, if necessary, and e!ecuted. Once it reads from the dis4, the pPcode is stored in the shared pool portion of the system global area #S32$, where it can be accessed by multiple users as needed. /i4e all of the contents of the shared pool, pPcode is aged out of the shared pool according to a least recently used #/RU$ algorithm. Subprograms can be local. /ocal subprograms must be declared in the declarati)e section of -/SS./ bloc4 and called from the e!ecutable section. Subprograms can not ha)e the declarati)e section separately. Stored subprograms can ha)e local subprograms' /ocal subprograms also can ha)e local subprograms. (f the subprogram contains a )ariable with the same name as the column name of the table then use the dot method to differentiate #subprogram_name.sal$. Subprograms can be in)alidated. -ROC 6UR S F 1U7C+(O7S -rocedures may return through out and in out parameters where as function must return. -rocedures can not ha)e return clause where as functions must. :e can use call statement directly for e!ecuting procedure where as we need to declare a )ariable in case of functions. 1unctions can use in select statements where as procedures can not. 1unctions can call from reports en)ironment where as procedures can not. :e can use e!ec for e!ecuting procedures where as functions can not. 1unction can be used in dbms5output where as procedure can not. -rocedure call is a standalone e!ecutable statement where as function call is a part of an e!ecutable statement.

S+OR 6 F /OC2/ SUB-RO3R2;S +he stored subprogram is stored in compiled pPcode in the database, when the procedure is called it does not ha)e to be compiled. +he local subprogram is compiled as part of its containing bloc4. (f the containing bloc4 is anonymous and is run multiple times, the subprogram has to be compiled each time. Stored subprograms can be called from any bloc4 submitted by a user who has e!ecute pri)ileges on the subprogram. /ocal subprograms can be called only from the bloc4 containing the subprogram. By 4eeping the stored subprogram code separate from the calling bloc4, the calling bloc4 is shorter and easier to understand. +he local subprogram and the calling bloc4 are one and the same, which can lead to part confusion. (f a change to the calling bloc4 is made, the subprogram will be recompiled as of the recompilation of the containing bloc4. +he compiled pPcode can be pinned in the shared pool using the 6B;S5SH2R 65-OO/ -ac4age. +his can impro)e performance. /ocal subprograms cannot be pinned in the shared pool by themsel)es. Stand alone stored subprograms can not be o)erloaded, but pac4aged subprograms can be o)erloaded within the same pac4age. /ocal subprograms can be o)erloaded within the same bloc4. !C"
CR 2+ B 3(7 76' OR R -/2C -ROC 6UR - (S

dbms5output.put5line#<Stored subprogram<$'

Output" S./9 e!ec p Stored subprogram !@"


6 C/2R -ROC 6UR B 3(7 76' B 3(7 76' - (S

dbms5output.put5line#</ocal subprogram<$'

p'

Output" /ocal subprogram CO;-(/(73 SUB-RO3R2;S


S./9 S./9

2lter procedure -C compile' 2lter function 1C compile'

SUB-RO3R2;S 6 - 76 C( S

2 stored subprogram is mar4ed as in)alid in the data dictionary if it has compile errors. 2 stored subprogram can also become in)alid if a 66/ operation is performed on one of its dependent obGects. (f a subprogram is in)alidated, the -/SS./ engine will automatically attempt to recompile in the ne!t time it is called. (f we ha)e two procedures li4e -C and -@ in which -C depends on -@. (f we compile -@ then -C is in)alidated. SUB-RO3R2;S 6 - 76 7C( S (7 R ;O+ 62+2B2S S

:e will call remote subprogram using connect string li4e -C\ OR2C/ ' (f we ha)e two procedures li4e -C and -@ in which -C depends on -@ but -@ was in remote database. (f we compile -@ it will not in)alidate -C immediately because the data dictionary does not trac4 remote dependencies. (nstead the )alidity of remote obGects is chec4ed at runtime. :hen -C is called, the remote data dictionary is queried to determine the status of -@. -C and -@ are compared to see it -C needs to be recompiled, there are two different methods of comparision +imestamp ;odel Signature ;odel +(; S+2;- ;O6 /

+his is the default model used by oracle. :ith this model, the timestamps of the last modifications of the two obGects are compared. +he last_ddl_time field of user_ob'ects contains the timestamp. f the base obGect has a newer timestamp than the dependent obGect, the dependent obGect will be recompiled.
(SSU S :(+H +H(S ;O6 /

(f the obGects are in different time 0ones, the comparison is in)alid. :hen -C is in a client side -/SS./ engine such as oracle forms, in this case it may not possible to recompile -C, because the source for it may not be included with the forms. S(372+UR ;O6 /

:hen a procedure is created, a signature is stored in the data dictionary in addition to the pPcode. +he signature encodes the types and order of the parametes. :hen -C is compiled the first time, the signature of -@ is included. +hus, -C only needs to recompiled when the signature of -@ changes. (n order to use the signature model, the parameter R ;O+ 56 - 76 7C( S5;O6 must be set to S(372+UR . +his is a parameter in the database initiali0ation file.
+HR :2,S O1 S ++(73 +H(S ;O6

2dd the line R ;O+ 56 - 76 7C( S5;O6 =S(372+UR to the database initiali0ation file. +he ne!t time the database is started, the mode will be set to S(372+UR for all sessions. 2lter system set remote5dependencies5mode = signature'

+his will affect the entire database #all sessions$ from the time the statement is issued. ,ou must ha)e the 2/+ R S,S+ ; pri)ilege to issue this command. 2lter session set remote5dependencies5mode = signature' +his will only affect your session
(SSU S :(+H +H(S ;O6 /

Signatures donUt get modified if the default )alues of formal parameters are changed. Suppose -@ has a default )alue for one of its parameters, and -C is using this default )alue. (f the default in the specification for -@ is changed, -C will not be recompiled by default. +he old )alue for the default parameter will still be used until -C is manually recompiled. (f -C is calling a pac4aged procedure -@, and a new o)erloaded )ersion of -@ is added to the remote pac4age, the signature is not changed. -C will still use the old )ersion#not the new o)erloaded one$ until -C is recompiled manually. 1OR:2R6 6 C/ R2+(O7 Before going to use the procedure in any other subprogram or other bloc4 , you must declare the prototype of the procedure in declarati)e section. !C"
-ROC 6UR B 3(7 6 C/2R -C (S

dbms5output.put5line#<1rom procedure pC<$' p@'


76 -C' -ROC 6UR B 3(7 -@ (S

76 -@' -ROC 6UR B 3(7 76 -D' B 3(7

dbms5output.put5line#<1rom procedure p@<$' pD'


-D (S

dbms5output.put5line#<1rom procedure pD<$'

pC'

76'

Output" p@' & RROR at line K" OR2PAJKKA" line K, column C" -/SPAADCD" <-@< not declared in this scope OR2PAJKKA" line K, column C" -/SS./" Statement ignored OR2PAJKKA" line CA, column C" -/SPAADCD" <-D< not declared in this scope OR2PAJKKA" line CA, column C" -/SS./" Statement ignored

!@"
6 C/2R -ROC 6UR -ROC 6UR -ROC 6UR B 3(7 -@' PP -D' -C (S

forward declaration

76 -C' -ROC 6UR B 3(7

dbms5output.put5line#<1rom procedure pC<$' p@'


-@ (S

dbms5output.put5line#<1rom procedure p@<$' pD'


76 -@' -ROC 6UR B 3(7 76 -D' B 3(7 76' -D (S

dbms5output.put5line#<1rom procedure pD<$'

pC'

Output" 1rom procedure pC 1rom procedure p@ 1rom procedure pD

-R(F(/ 3 S 276 S+OR 6 SUB-RO3R2;S


N CU+ -R F(/ 3

1or stored subprograms and pac4ages the rele)ant pri)ilege is N CU+ . (f user 2 had the procedure called emp5proc then user 2 grants e!ecute pri)ilege on procedure to user B with the following command. S./9 3rant e!ecute on emp5proc to user B. +hen user B can run the procedure by issuing S./9 !ec user 2.emp5proc user2 created the following procedure
CR 2+ B 3(7 OR R -/2C -ROC 6UR - (S

cursor is select &from studentC' for ) in c loop insert into student@ )alues#).no,).name,).mar4s$' end loop'

76 -'

user2 granted e!ecute pri)ilege to userB using S./9 grant e!ecute on p to userB +hen userB e!ecuted the procedure

S./9

!ec user2.p

(f suppose userB also ha)ing student@ table then which table will populate whether user2Us or userBUs. +he answer is user2Us student@ table only because by default the procedure will e!ecute under the pri)lige set of its owner. +he abo)e procedure is 4nown as definerUs procedure.
HO: +O -O-U/2+ US R BUs +2B/

Oracle introduces #nvoker(s and Definer(s rights) By default it will use the definerUs rights. 2n in)o4erUs rights routine can be created by using 2U+H(6 clause to populate the userBUs table. (t is )alid for standPalone subprograms, pac4age specifications, and obGect type specifications only. user2 created the following procedure
CR 2+ OR R -/2C -ROC 6UR 2U+H(6 CURR 7+5US R (S B 3(7 -

cursor is select &from studentC' for ) in c loop insert into student@ )alues#).no,).name,).mar4s$' end loop'

76 -'

+hen grant e!ecute pri)ilege on p to userB. !ecuting the procedure by userB, which populates userBUs table. +he abo)e procedure is called in)o4erUs procedure. (nstead of current5user of authid clause, if you use definer then it will be called definerU procedure.
S+OR 6 SUB-RO3R2;S 276 RO/ S

we ha)e two users sa4eth and sudha in which sa4eth has student table and sudha does not. Sudha is going to create a procedure based on student table owned by sa4eth. Before doing this sa4eth must grant the permissions on this table to sudha. conn sa4ethSsa4eth grant all on student to sudha' then sudha can create procedure S./9 conn sudhaSsudha
S./9 S./9 CR 2+

cursor c is select &from sa4eth.student' for ) in c loop

OR R -/2C

-ROC 6UR

- (S

B 3(7

dbms5output.put5line#T7o = T >> ).no$' end loop'


76 -'

here procedure will be created. (f the same pri)ilege was granted through a role it wont create the procedure. !amine the following code conn sa4ethSsa4eth create role sa4eth5role' S./9 grant all on student to sa4eth5role' S./9 grant sa4eth5role to sudha' then conn sudhaSsudha
S./9 S./9 CR 2+ B 3(7 OR R -/2C -ROC 6UR - (S

cursor c is select &from sa4eth.student' for ) in c loop dbms5output.put5line#T7o = T >> ).no$' end loop'

76 -'

+he abo)e code will raise error instead of creating procedure . +his is because of early binding which -/SS./ uses by default in which references are e)aluated in compile time but when you are using a role this will affect immediately.
(SSU S :(+H (7FOB RUS R(3H+S

(n an in)o4erUs rights routine, e!ternal references in S./ statements will be resol)ed using the callerUs pri)ilege set. But references in -/SS./ statements are still resol)ed under the ownerUs pri)ilege set.
+R(33 RS, F( :S 276 (7FOB RUS R(3H+S

2 database trigger will always be e!ecuted with definerUs rights and will e!ecute under the pri)ilege set of the schema that owns the triggering table. +his is also true for -/SS./ function that is called from a )iew. (n this case, the function will e!ecute under the pri)ilege set of the )iewUs owner.

-2CB23 S
2 package is a container for related obGects. (t has specification and body. is stored separately in data dictionary. -2CB23 S,7+2N ach of them

Create or replace pac4age 8package_name9 is PP pac4age specification includes subprograms signatures, cursors and global or public )ariables.

nd 8package_name9' Create or replace pac4age body 8package_name9 is PP pac4age body includes body for all the subprograms declared in the spec, pri)ate Fariables and cursors. Begin PP initiali0ation section !ception PP !ception handling seciton nd 8package_name9' (;-OR+27+ -O(73S 2BOU+ -2CB23 S +he first time a pac4aged subprogram is called or any reference to a pac4aged )ariable or type is made, the pac4age is instantiated. ach session will ha)e its own copy of pac4aged )ariables, ensuring that two sessions e!ecuting subprograms in the same pac4age use different memory locations. (n many cases initiali0ation needs to be run the first time the pac4age is instantiated within a session. +his can be done by adding initiali0ation section to the pac4age body after all the obGects. -ac4ages are stored in the data dictionary and can not be local. -ac4aged subprograms has an ad)antage o)er stand alone subprogram. :hen e)er any reference to pac4age, the whole pac4age pPcode was stored in shared pool of S32. -ac4age may ha)e local subprograms. ,ou can include authid clause inside the pac4age spec not in the body. +he e!ecution section of a pac4age is 4now as initiali0ation section. ,ou can ha)e an e!ception section at the bottom of a pac4age body. -ac4ages subprograms are not in)alidated. CO;-(/(73 -2CB23 S
S./9 S./9 S./9

2lter pac4age -B3 compile' 2lter pac4age -B3 compile specification' 2lter pac4age -B3 compile body' 6 - 76 7C( S

-2CB23

+he pac4age body depends on the some obGects and the pac4age header. +he pac4age header does not depend on the pac4age body, which is an ad)antage of pac4ages. :e can change the pac4age body with out changing the header. -2CB23 RU7+(; S+2+

-ac4age runtime state is differ for the following pac4ages. Serially reusable pac4ages 7on serially reusable pac4ages
S R(2//, R US2B/ -2CB23 S

+o force the oracle to use serially reusable )ersion then include -R23;2 S in both pac4age spec and body, !amine the following pac4age.
CR 2+ OR R -/2C -2CB23 -B3 (S

R(2//,5R US2B/

pragma serially5reusable' procedure emp5proc'


76 -B3'

CR 2+

OR R -/2C

-2CB23

BO6, -B3 (S

pragma serially5reusable' cursor c is select ename from emp'


-ROC 6UR

)5ename emp.ename%type' )5flag boolean "= true' )5numrows number "= A'

;-5-ROC (S

B 3(7

if not c%isopen then open c' end if' while )5flag loop fetch c into )5ename' )5numrows "= )5numrows ] C' if )5numrows = K then )5flag "= false' end if' dbms5output.put5line#< name = < >> )5ename$' end loop'

76 ;-5-ROC' 76 -B3' S./9

e!ec p4g.emp5proc name = S;(+H name = 2// 7 name = :2R6 name = HO7 S name = ;2R+(7

S./9

e!ec p4g.emp5proc name = S;(+H name = 2// 7 name = :2R6 name = HO7 S name = ;2R+(7

+he abo)e pac4age displays the same output for each e!ecution e)en though the cursor is not closed. Because the serially reusable )ersion resets the state of the cursor each time it was called.
7O7 S R(2// , R US2B/ -2CB23 S

+his is the default )ersion used by the oracle, e!amine the following pac4age.
CR 2+

procedure emp5proc'
OR R -/2C -2CB23

OR R -/2C

-2CB23

-B3 (S

76 -B3' CR 2+ BO6, -B3 (S

cursor c is select ename from emp' )5ename emp.ename%type' )5flag boolean "= true' )5numrows number "= A'
;-5-ROC (S

-ROC 6UR

B 3(7

if not c%isopen then open c' end if' while )5flag loop fetch c into )5ename' )5numrows "= )5numrows ] C' if )5numrows = K then )5flag "= false' end if' dbms5output.put5line#< name = < >> )5ename$' end loop'

76 ;-5-ROC' 76 -B3' S./9

e!ec p4g.emp5proc name = S;(+H name = 2// 7 name = :2R6 name = HO7 S name = ;2R+(7 e!ec p4g.emp5proc = = = = =
B/2B C/2RB SCO++ B(73 +UR7 R

S./9

name name name name name

+he abo)e pac4age displays the different output for each e!ecution e)en though the cursor is not closed. Because the nonPserially reusable )ersion remains the state of the cursor o)er database calls.
6 - 76 7C( S O1 -2CB23 RU7+(; S+2+

6ependencies can e!ists between pac4age state and anonymous bloc4s. !amine the following program Create this pac4age in first session
CR 2+ OR R -/2C -2CB23 -B3 (S

) number "= K' procedure p'


76 -B3' CR 2+ OR R -/2C -ROC 6UR - (S B 3(7 -2CB23 BO6, -B3 (S

dbms5output.put5line#<) = < >> )$' ) "= CA' dbms5output.put5line#<) = < >> )$'
76 -' 76 -B3'

Connect to second session, run the following code.


B 3(7 76'

p4g.p'

+he abo)e code wil wor4. 3o bac4 to first session and recreate the pac4age using create. +hen connect to second session and run the following code again.
B 3(7

p4g.p'
76'

+his abo)e code will not wor4 because of the following. +he anonymous bloc4 depends on p4g. +his is compile time dependency. +here is also a runtime dependency on the pac4aged )ariables, since each session has its own copy of pac4aged )ariables. +hus when p4g is recompiled the runtime dependency is followed, which in)alidates the bloc4 and raises the oracle error. Runtime dependencies e!ist only on pac4age state. +his includes )ariables and cursors declared in a pac4age. (f the pac4age had no global )ariables, the second e!ecution of the anonymous bloc4 would ha)e succeeded. -UR(+, / F /S (n general, calls to subprograms are procedural, they cannot be called from S./ statements. Howe)er, if a standPalone or pac4aged function meets certain restrictions, it can be called during e!ecution of a S./ statement. UserPdefined functions are called the same way as builtPin functions but it must meet different restrictions. +hese restrictions are defined in terms of purity le)els. +here are four types of purity le)els. :76S PP :rites 7o 6atabase State R76S PP Reads 7o 6atabase State :7-S PP :rites 7o -ac4age State

R7-S

PP

Reads 7o -ac4age State

(n addition to the preceding restrictions, a userPdefined function must also meet the following requirements to be called from a S./ statement. +he function has to be stored in the database, either standPalone or as part of a pac4age. +he function can ta4e only in parametes. +he formal parameters must use only database types, not -/SS./ types such as boolean or record. +he return type of the function must also be a database type. +he function must not end the current transaction with commit or rollbac4, or rollbac4 to a sa)epoint prior to the function e!ecution. (t also must not issue any alter session or alter system commands.
R S+R(C+5R 1 R 7C S

1or pac4aged functions, howe)er, the the purity le)el of a gi)en function. Synta!"

R S+R(C+5R 1 R 7C S

pragma is required to specify

-R23;2 R S+R(C+5R 1 R 7C S#subprogram_name

Q,R76SR Q,R7-SR$'

or package_name,

:76S Q,:7-SR

CR 2+

!"

OR R -/2C

-2CB23

-B3 (S

function funC return )archar' pragma restrict5references#funC,wnds$' function fun@ return )archar' pragma restrict5references#fun@,wnds$'
76 -B3' CR 2+ OR R -/2C -2CB23 BO6, -B3 (S 1U7C+(O7 1U7C return )archar (S B 3(7

76 1U7C' 1U7C+(O7 1U7@ B 3(7

update dept set deptno = CC' return <hello<' return )archar


(S

update dept set dname =<aa<' return <hello<'


76 1U7@' 76 -B3'

+he abo)e pac4age body will not created, it will gi)e the following erros. -/SPAAEK@" Subprogram <1U7C< )iolates its associated pragma -/SPAAEK@" Subprogram <1U7@< )iolates its associated pragma
CR 2+ OR R -/2C -2CB23 BO6, -B3 (S 1U7C+(O7 1U7C return )archar (S B 3(7

76 1U7C' 1U7C+(O7 1U7@ B 3(7 76 1U7@' 76 -B3'

return <hello<' return )archar


(S

return <hello<'

7ow the pac4age body will be created.


6 12U/+

(f there is no R S+R(C+5R 1 R 7C S pragma associated with a gi)en pac4aged function, it will not ha)e any purity le)el asserted. Howe)er, you can change the default purity le)el for a pac4age. +he 6 12U/+ 4eyword is used instead of the subprogram name in the pragma. !"
CR 2+

pragma restrict5references#default,wnds$' function funC return )archar' function fun@ return )archar'
OR R -/2C -2CB23 BO6, -B3 (S 1U7C+(O7 1U7C return )archar (S B 3(7

OR R -/2C

-2CB23

-B3 (S

76 -B3' CR 2+

76 1U7C' 1U7C+(O7 1U7@ B 3(7

update dept set deptno = CC' return <hello<' return )archar


(S

update dept set dname =<aa<' return <hello<'


76 1U7@' 76 -B3'

+he abo)e pac4age body will not created, it will gi)e the following erros because the pragma will apply to all the functions. -/SPAAEK@" Subprogram <1U7C< )iolates its associated pragma -/SPAAEK@" Subprogram <1U7@< )iolates its associated pragma
CR 2+ OR R -/2C -2CB23 BO6, -B3 (S 1U7C+(O7 1U7C return )archar (S B 3(7 76 1U7C' 1U7C+(O7 1U7@ B 3(7 76 1U7@' 76 -B3'

return <hello<' return )archar


(S

return <hello<'

7ow the pac4age body will be created.

+RUS+

(f the +RUS+ 4eyword is present, the restrictions listed in the pragma are not enforced. Rather, they are trusted to be true. !"
CR 2+

76 -B3' CR 2+

function funC return )archar' pragma restrict5references#funC,wnds,trust$' function fun@ return )archar' pragma restrict5references#fun@,wnds,trust$'
OR R -/2C -2CB23 BO6, -B3 (S 1U7C+(O7 1U7C return )archar (S B 3(7

OR R -/2C

-2CB23

-B3 (S

update dept set deptno = CC' return <hello<'


76 1U7C' 1U7C+(O7 1U7@ B 3(7

return )archar

(S

76 1U7@' 76 -B3'

update dept set dname =<aa<' return <hello<'

+he abo)e pac4age will be created successfully.


(;-OR+27+ -O(7+S 2BOU+ R S+R(C+5R 1 R 7C S

+his pragma can appear anywhere in the pac4age specification, after the function declaration. (t can apply to only one function definition. 1or o)erload functions, the pragma applies to the nearest definition prior to the -ragma. +his pragma is required only for pac4ages functions not for standPalone functions. +he -ragma can be declared only inside the pac4age specification. +he pragma is chec4ed at compile time, not runtime. (t is possible to specify without any purity le)els when trust or combination of default and trust 4eywords are present. -(77(73 (7 +H SH2R 6 -OO/

+he shared pool is the portion of the S3S that contains, among other things, the pPcode of compiled subprograms as they are run. +he first time a stored a store subprogram is called, the pPcode is loaded from dis4 into the shared pool. Once the obGect is no longer referenced, it is free to be aged out. ObGects are aged out of the shared pool using an /RU#/east Recently Used$ algorithm.

+he 6B;S5SH2R 65-OO/ pac4age allows you to pin obGects in the shared pool. :hen an obGect is pinned, it will ne)er be aged out until you request it, no matter how full the pool gets or how often the obGect is accessed. +his can impro)e performance, as it ta4es time to reload a pac4age from dis4.
6B;S5SH2R 65-OO/

has four procedures

B U7B S(? S 2BOR+ 65R .U S+5+HR SHO/6 B 6B;S5SH2R 65-OO/.B -

+he

procedure is used to pin obGects in the pool.

Synta!"
-ROC 6UR B -#ob'ect_name

)archar@,flag char default T-U$'

Here the flag represents different types of flag )alues for different types of obGects. . R C + HS HC HR H6
U7B U7B -

PP PP PP PP PP PP PP PP PP

-ac4age, function or procedure Sequence +rigger S./ Cursor ObGect type Ha)a source Ha)a class Ha)a resource Ha)a shared data

- is the only way to remo)e a 4ept obGect from the shared pool, without restarting the database. Bept obGects are ne)er aged out automatically.

Synta!"
-ROC 6UR S(? S S(? S U7B -#ob'ect_name

)archar@, flag char default T-U$'

will echo the contents of the shared pool to the screen.

Synta!"

-ROC 6UR S(? S#minsi!e number$' ObGects with greater than the minsi!e will be returned. the data. 2BOR+ 65R .U S+5+HR SHO/6

S(? S

uses

6B;S5OU+-U+

to return

:hen the database determines that there is not enough memory in the shared pool to satisfy a gi)en request, it will begin aging obGects out until there is enough memory. (t enough obGects are aged out, this can ha)e a performance impact on other database sessions. +he 2BOR+ 65R .U S+5+HR SHO/6 can be used to remedy this. Synta!"
-ROC 6UR 2BOR+ 65R .U S+5+HR SHO/6#threshold_si!e

number$'

Once this procedure is called, oracle will not start aging obGects from the pool unless at least threshold_si!e bytes is needed. 62+2 ;O6 / 1OR SUB-RO3R2;S 276 -2CB23 S US R5OBH C+S US R5SOURC US R5 RRORS 6B25OBH C+S 6B25SOURC 6B25 RRORS 2//5OBH C+S 2//5SOURC 2//5 RRORS

2U+O7O;OUS +R27S2C+(O7 -rior to OracleIi, there was no way in which some S./ operations within a transaction could be committed independent of the rest of the operations. Oracle allows this, howe)er, through autonomous transactions. 2n autonomous transaction is a transaction that is started within the conte!t of another transaction, 4nown as parent transaction, but is independent of it. +he autonomous transaction can be committed or rolled bac4 regardless ot the state of the parent transaction. !"
CR 2+ 6 C/2R B 3(7

after insert on student

OR R -/2C

+R(33 R 2U+O7O;OUS5+R27S2C+(O75+R(33 R

pragma autonomous5transaction' update student set mar4s = KKK' commit'

76 2U+O7O;OUS5+R27S2C+(O75+R(33 R'

Output"
S./9

select & from student' 72 ;2RBS PPPPP PP PPPPPPPPPP a CCC b @@@

7O PPPPP C @

D
S./9 S./9

DAA

insert into student )alues#E,<d<,EEE$' select & from student' 7O PPPP C @ D E 72 ;2RBS PPPPPP PP PPPPPPPPPP a KKK b KKK c KKK d EEE

R S+R(C+(O7S O7 2U+O7O;OUS +R27S2C+(O7

(f an autonomous transaction attempts to access a resource held by the main transaction, a deadloc4 can occur in you program. ,ou cannot mar4 all programs in a pac4age as autonomous with a single -R23;2 declaration. ,ou must indicate autonomous transactions e!plicity in each program. +o e!it without errors from an autonomous transaction program that has e!ecuted at least one (7S R+ or U-62+ or 6 / + , you must perform an e!plicit commit or rollbac4. +he CO;;(+ and RO//B2CB statements end the acti)e autonomous transaction, but they do not force the termination of the autonomous routine. ,ou can ha)e multiple CO;;(+ andSor RO//B2CB statements inside your autonomous bloc4. ,ou can not rollbac4 to a sa)epoint set in the main transaction. +he +R27S2C+(O7S parameter in the oracle initiali0ation file specifies the ma!imum number of transactions allowed concurrently in a session. +he default )alue is MK for this, but you can increase the limit. ;U+2+(73 +2B/ S +here are restrictions on the tables and columns that a trigger body may access. (n order to define these restrictions, it is necessary to understand mutating and constraining tables. 2 mutating table is table that is currentlty being modified by a 6;/ statement and the trigger e)ent also 6;/ statement. 2 mutating table error occurs when a rowPle)el trigger tries to e!amine or change a table that is already undergoing change. 2 constraining table is a table that might need to be read from for a referential integrity constraint. !"
CR 2+ OR R -/2C +R(33 R ;U+2+(735+R(33 R

before delete on student for each row


6 C/2R

ct number'

B 3(7

select count#&$ into ct from student where no = "old.no'

76 ;U+2+(735+R(33 R'

Output" delete student where no = C' delete student where no = C & RROR at line C" OR2PAEALC" table SCO++.S+U6 7+ is mutating, triggerSfunction may not see it OR2PAJKC@" at XSCO++.+X, line E OR2PAEAII" error during e!ecution of trigger <SCO++.+<
S./9 HO: +O 2FO(6 ;U+2+(73 +2B/ RROR ^

By using autonomous transaction By using statement le)el trigger

Anda mungkin juga menyukai