Vous êtes sur la page 1sur 63

DBMS Unit 4

Procedural SQL Fundamentals: Part II

Procedural SQL Fundamentals Part II Procedure, Function, Package, Trigger


Table of Contents Procedures and Functions...........................................................................................................1 Overvie .............................................................................................................................1 !reatin" Procedure..............................................................................................................# Develo$in" Procedures.......................................................................................................% I& Parameters..............................................................................................................' OU( Parameters..........................................................................................................' I& OU( Parameters.....................................................................................................) D*F+UL( O$tion ,or Parameters.............................................................................1Invo.in" Procedure...........................................................................................................1/ Declarin" Su0$ro"rams.............................................................................................1/ Invo.in" a Procedure ,rom an +non1mous PL2SQL Bloc.......................................1# Invo.in" a Procedure ,rom +not3er Procedure........................................................1# 4emovin" Procedures...............................................................................................1# !reatin" Functions............................................................................................................14 Develo$ Stored Functions.................................................................................................1% *5ecutin" Functions..........................................................................................................1% Invo.in" Functions in SQL *5$ressions...................................................................16 4estrictions on !allin" Functions ,rom SQL *5$ressions.......................................17 4emovin" Functions.................................................................................................1' !om$arin" Procedures and Functions..............................................................................1' Mana"in" Stored PL2SQL O08ects............................................................................................1' US*49OB:*!(S Data Dictionar1 ;ie ..........................................................................1' US*49SOU4!* Data Dictionar1 ;ie ...........................................................................1) US*49*44O4S Data Dictionar1 ;ie ...........................................................................1) Summar1.........................................................................................................................../Pac.a"e...................................................................................................................................../Overvie o, Pac.a"es......................................................................................................./!reatin" Pac.a"es.............................................................................................................// !reatin" t3e Pac.a"e S$eci,ication...........................................................................// !reatin" t3e Pac.a"e Bod1......................................................................................./# Invo.in" Pac.a"e !onstructs............................................................................................/% Declarin" a Bodiless Pac.a"e.................................................................................../% 4emovin" Pac.a"es........................................................................................................../6 <uidelines ,or Develo$in" Pac.a"es................................................................................/7

DBMS Unit 4

Procedural SQL Fundamentals: Part II

ii

Oracle Su$$lied Pac.a"es................................................................................................./7 Usin" t3e DBMS9SQL Pac.a"e.............................................................................../' Usin" t3e DBMS9DDL Pac.a"e..............................................................................#Usin" DBMS9:OB ,or Sc3edulin"...........................................................................#Usin" t3e DBMS9OU(PU( Pac.a"e.......................................................................## U(L9FIL* Pac.a"e..................................................................................................## (3e U(L9=((P Pac.a"e..........................................................................................#7 Usin" t3e U(L9(!P Pac.a"e...................................................................................#' Ot3er Oracle>su$$lied $ac.a"es...............................................................................#' (ri""er.......................................................................................................................................4/ !reatin" DML (ri""ers.....................................................................................................4# Basic (ri""er S1nta5:................................................................................................4% !reatin" a DML 4o (ri""er...................................................................................47 I&S(*+D OF (ri""ers.....................................................................................................%1 !reatin" an I&S(*+D OF (ri""er...........................................................................%1 Di,,erentiatin" Bet een Data0ase (ri""ers and Stored Procedures.........................%7 Mana"in" (ri""er..............................................................................................................%7 Dis$la1in" (ri""er De,inition *rrors........................................................................%7 ;ie in" De,ined (ri""ers.........................................................................................%7 Dro$$in" (ri""ers.....................................................................................................%7 Disa0lin" (ri""ers.....................................................................................................%7 4ecom$ile a tri""er ,or a ta0le:.................................................................................%' +0ortin" (ri""ers it3 *rror....................................................................................%'

DBMS Unit 4

Procedural SQL Fundamentals: Part II

Procedures and Functions Overview PL2SQL Pro"ram !onstructs *ver1

PL2SQL construct is com$osed o, one or more 0loc.s. (3ese 0loc.s can 0e entirel1 se$arate or nested it3in one anot3er. (3ere,ore? one 0loc. can re$resent a small $art o, anot3er 0loc.? 3ic3 in turn can 0e $art o, t3e 3ole unit o, code. PL2SQL $rocedures 0e3ave ver1 muc3 li.e $rocedures? or su0>$ro"rams? in ot3er $ro"rammin" lan"ua"e. + su0$ro"ram: Is a named PL2SQL 0loc. t3at can acce$t $arameters and 0e invo.ed ,rom a callin" environment Is o, t o t1$es: + $rocedure t3at $er,orms an action + ,unction t3at com$utes a value Is 0ased on standard PL2SQL 0loc. structure Provides modularit1? reusa0ilit1? e5tensi0ilit1? and maintaina0ilit1 Provides eas1 maintenance? im$roved data securit1 and inte"rit1? im$roved $er,ormance? and im$roved code clarit1 Bloc. Structure ,or +non1mous PL2SQL Bloc.s

DECLARE (optional) Declare PL2SQL o08ects to 0e used it3in t3is 0loc. BEGIN (mandatory) De,ine t3e e5ecuta0le statements EXCEPTION (optional)

DBMS Unit 4

Procedural SQL Fundamentals: Part II

De,ine t3e actions t3at ta.e $lace i, an error or e5ce$tion arises END; (mandatory) (3e section 0et een t3e .e1 ords DECLARE and BEGIN is re,erred to as t3e declaration section. In t3e declaration section? 1ou de,ine t3e PL2SQL o08ects suc3 as varia0les? constants? cursors? and user>de,ined e5ce$tions t3at 1ou ant to re,erence it3in t3e 0loc.. (3e DECLARE .e1 ord is o$tional i, 1ou do not declare an1 PL2SQL o08ects. (3e BEGIN and END .e1 ords are mandator1 and enclose t3e 0od1 o, actions to 0e $er,ormed. (3is section is re,erred to as t3e e5ecuta0le section o, t3e 0loc.. (3e section 0et een EXCEPTION and END is re,erred to as t3e e5ce$tion section. (3e e5ce$tion section tra$s error conditions. In it? 1ou de,ine actions to ta.e i, t3e s$eci,ied condition arises. (3e e5ce$tion section is o$tional. (3e .e1 ords DECLARE? BEGIN? and EXCEPTION are not ,ollo ed 01 semicolons? 0ut END and all ot3er PL2SQL statements do re@uire semicolons. Bloc. Structure ,or PL2SQL Su0$ro"rams

<h ad r! ""# I$ # A$ ""# $%&pro'ram $p (i)i(ation D (laration * (tion "# BEGIN "# E+ (%ta&l * (tion "# EXCEPTION (optional) "# $%&pro'ram Body E+( ption * (tion "# END; "# Su0$ro"ram S$eci,ication (3e 3eader is relevant ,or named 0loc.s onl1 and determines t3e a1 t3at t3e $ro"ram unit is called or invo.ed. (3e 3eader determines: (3e PL2SQL su0$ro"ram t1$e? t3at is? eit3er a $rocedure or a ,unction (3e name o, t3e su0$ro"ram (3e $arameter list? i, one e5ists (3e RET,RN clause? 3ic3 a$$lies onl1 to ,unctions (3e I$ or A$ .e1 ord is mandator1. Su0$ro"ram Bod1 (3e declaration section o, t3e 0loc. 0et een I$#A$ and BEGIN. (3e .e1 ord DECLARE t3at is used to indicate t3e startin" o, t3e declaration section in anon1mous 0loc.s is not used 3ere. (3e e5ecuta0le section 0et een t3e BEGIN and END .e1 ords is mandator1?

DBMS Unit 4

Procedural SQL Fundamentals: Part II

enclosin" t3e 0od1 o, actions to 0e $er,ormed. (3ere must 0e at least one statement e5istin" in t3is section. (3ere s3ould 0e at least a N,LLA statement? t3at is considered an e5ecuta0le statement. (3e e5ce$tion section 0et een EXCEPTION and END is o$tional. (3is section tra$s $rede,ined error conditions. In t3is section? 1ou de,ine actions to ta.e i, t3e s$eci,ied error condition arises. B3en a se@uence o, statements is re$eated more t3an once in a PL2SQL su0$ro"ram? 1ou can create a su0$ro"ram it3 t3e re$eated code. Cou can invo.e t3e su0$ro"ram at multi$le locations in a PL2SQL 0loc.. +,ter t3e su0$ro"ram is created and stored in t3e data0ase? it can 0e invo.ed an1 num0er o, times and ,rom multi$le a$$lications. =ere is an e5am$le o, a PL2SQL $rocedure addtu$le1 t3at? "iven an inte"er i? inserts t3e tu$le Di? E555EF into t3e ,ollo in" e5am$le relation:

CREATE TABLE T- ( a INTEGER. & C/AR(01) ); CREATE PROCED,RE addt%pl 0(i IN N,2BER) A$ BEGIN IN$ERT INTO T- 3AL,E$(i. 4+++4); END addt%pl 0; (o ,ind out 3at $rocedures and ,unctions 1ou 3ave created? use t3e ,ollo in" SQL @uer1:

$5L! $ELECT o&6 (t7typ . o&6 (t7nam - 8RO2 %* r7o&6 (t* 9 :/ERE o&6 (t7typ ; 4PROCED,RE4 < OR o&6 (t7typ ; 48,NCTION4; (o ,i"ure our $rocedures e5istin" in t3e sc3ema? c3ec. user9$rocedures 8RO2 %* r7pro( d%r * ; $5L! DE$C %* r7pro( d%r * $5L! $ELECT o&6 (t7nam . pro( d%r 7nam (o dro$ a stored $rocedure2,unction: $5L! DROP PROCED,RE procedure_name; $5L! DROP 8,NCTION function_name; Creating Procedure + $rocedure is a t1$e o, su0$ro"ram t3at $er,orms an action.

DBMS Unit 4

Procedural SQL Fundamentals: Part II

+ $rocedure can 0e stored in t3e data0ase? as a sc3ema o08ect? ,or re$eated e5ecution. + $rocedure is introduced 01 t3e .e1 ords CREATE PROCED,RE ,ollo ed 01 t3e $rocedure name and its $arameters. +n o$tion is to ,ollo CREATE 01 OR REPLACE. (3e advanta"e o, doin" so is t3at s3ould 1ou 3ave alread1 made t3e de,inition? 1ou ill not "et an error. On t3e ot3er 3and? s3ould t3e $revious de,inition 0e a di,,erent $rocedure o, t3e same name? 1ou ill not 0e arned? and t3e old $rocedure ill 0e lost. (3ere can 0e an1 num0er o, $arameters? eac3 ,ollo ed 01 a mode and a t1$e. (3e $ossi0le modes are IN Dread>onl1F? O,T D rite>onl1F? and IN O,T Dread and riteF. Note: (3e t1$e s$eci,ier in a $arameter declaration must 0e unconstrained. For e5am$le? C/AR(01) and 3ARC/AR(-1) are ille"alA C/AR or 3ARC/AR s3ould 0e used instead. (3e S1nta5 ,or !reatin" Procedures

$ynta+= CREATE >OR REPLACE? PROCED,RE procedure_name >(param t r0 >mod 0? datatyp 0. param t r- >mod -? datatyp -. @ @ @)? I$#A$ PLA$5L Blo(B; S1nta5 De,initions Parameter parameter mode Description &ame o, a PL2SQL varia0le 3ose value is $assed to or $o$ulated 01 t3e callin" environment? or 0ot3? de$endin" on t3e mode 0ein" used (1$e o, ar"ument: IN Dde,aultF OU( I& OU( Data t1$e o, t3e ar"umentcan 0e an1 SQL 2 PLSQL data t1$e. !an 0e o, CTDPE? CRO:TDPE? or an1 scalar or com$osite data t1$e. procedure_name &ame o, t3e $rocedure

Data type PL/SQL block

Procedural 0od1 t3at de,ines t3e action $er,ormed 01 t3e $rocedure PL2SQL 0loc.s start it3 eit3er BEGIN or t3e declaration o, local varia0les and end it3 eit3er END or END $rocedure9name. Cou cannot re,erence 3ost or 0ind varia0les in t3e PL2SQL 0loc. o, a stored $rocedure. (3e REPLACE o$tion indicates t3at i, t3e $rocedure e5ists? it ill 0e dro$$ed and re$laced it3 t3e ne version created 01 t3e statement. Cou cannot restrict t3e siGe o, t3e data t1$e in t3e $arameters.

DBMS Unit 4

Procedural SQL Fundamentals: Part II

Developing Procedures Follo in" are t3e main ste$s ,or develo$in" a stored $rocedure.

1.

Write the syntax: *nter t3e code to create a $rocedure in a s1stem editor or ord $rocessor and save it as a SQL scri$t ,ile D.s@l e5tensionF. /. Compile the code: Usin" iSQLHPlus? load and run t3e SQL scri$t ,ile. (3e source code is com$iled into P code and t3e $rocedure is created. In iSQLHPlus? use $/O: ERROR$ to see an1 com$ilation errors. Fi5 t3e errors in t3e code usin" t3e editor and recom$ile t3e code. #. *5ecute t3e $rocedure to $er,orm t3e desired action. +,ter t3e source code is com$iled and t3e $rocedure is success,ull1 created? t3e $rocedure can 0e e5ecuted an1 num0er o, times usin" t3e EXEC,TE command ,rom iSQLHPlus. (3e PL2SQL com$iler "enerates t3e pseudocode or P code? 0ased on t3e $arsed code. (3e PL2SQL en"ine e5ecutes t3is 3en t3e $rocedure is invo.ed. &ote: I, t3ere are an1 com$ilation errors? and 1ou ma.e su0se@uent c3an"es to t3e CREATE PROCED,RE statement? 1ou must eit3er DROP t3e $rocedure ,irst? or use t3e OR REPLACE s1nta5. Formal ;ersus +ctual Parameters Formal $arameters: varia0les declared in t3e $arameter list o, a su0$ro"ram s$eci,ication. For e5am$le? in t3e $rocedure RAI$E7$AL 0elo ? t3e varia0les P7ID and P7A2O,NT are ,ormal $arameters.

DBMS Unit 4

Procedural SQL Fundamentals: Part II

CREATE PROCED,RE rai* 7*al(p7id N,2BER. p7amo%nt N,2BER) @@@ END rai* 7*al; +ctual $arameters: varia0les or e5$ressions re,erenced in t3e $arameter list o, a su0$ro"ram call. For e5am$le? in t3e call rai* 7*al(E7id . -111) to t3e $rocedure RAI$E7$AL? t3e varia0le 37ID and -111 are actual $arameters. Met3ods ,or Passin" Parameters Positional: List actual $arameters in t3e same order as ,ormal $arametersA i.e.? lists values in t3e order in 3ic3 t3e $arameters are declared. &amed: List actual $arameters in ar0itrar1 order 01 associatin" eac3 it3 its corres$ondin" ,ormal $arameter. It lists values in ar0itrar1 order 01 associatin" eac3 one it3 its $arameter name? usin" s$ecial s1nta5 DIJF !om0ination: List some o, t3e actual $arameters as $ositional and some as named. Lists t3e ,irst values $ositionall1? and t3e remainder usin" t3e s$ecial s1nta5 o, t3e named met3od. Procedural Parameter Modes IN (d )a%lt) Passes a constant value ,rom t3e callin" environment into t3e $rocedure O,T Passes a value ,rom t3e $rocedure to t3e callin" environment IN O,T Passes a value ,rom t3e callin" environment into t3e $rocedure and a $ossi0l1 di,,erent value ,rom t3e $rocedure 0ac. to t3e callin" environment usin" t3e same $arameter Note: D+(+(CP* can 0e onl1 t3e CTDPE de,inition? t3e CRO:TDPE de,inition? or an e5$licit data t1$e it3 no siGe s$eci,ication. !reatin" Procedures it3 Parameters IN O,T IN O,T Must 0e s$eci,ied 4eturned to callin" environment UninitialiGed varia0le Must 0e s$eci,ied Passed into su0$ro"ramA returned to callin" environment InitialiGed varia0le Must 0e a varia0le

De,ault mode ;alue is $assed into su0$ro"ram Formal $arameter acts as a constant

+ctual $arameter can 0e a Must 0e a varia0le literal? e5$ression? constant? or initialiGed varia0le !an 0e assi"ned a de,ault value !annot 0e assi"ned a de,ault value

!annot 0e assi"ned a de,ault value

DBMS Unit 4

Procedural SQL Fundamentals: Part II

+ @uic. e5am$le: (3e ,ollo in" $rocedure also inserts a tu$le into (/? 0ut it ta.es 0ot3 com$onents as ar"uments:

CREATE PROCED,RE addt%pl -( + T-@aCTDPE. y T-@&CTDPE) A$ BEGIN IN$ERT INTO T-(a. &) 3AL,E$(+. y); END addt%pl -; A &o ? to add a tu$le D1-? Ea0cEF to (/: BEGIN addt%pl -(01. 4a&(4); END; A (3e ,ollo in" illustrates t3e use o, an O,T $arameter: CREATE TABLE T9 ( a INTEGER. & INTEGER ); CREATE PROCED,RE addt%pl 9(a N,2BER. & O,T N,2BER) A$ BEGIN & =; <; IN$ERT INTO T9 3AL,E$(a. &); END; A *5ecute t3e $rocedure DECLARE E N,2BER; BEGIN addt%pl 9(01. E); END; A

DBMS Unit 4

Procedural SQL Fundamentals: Part II

'

&ote t3at assi"nin" values to $arameters declared as O,T or IN O,T causes t3e corres$ondin" in$ut ar"uments to 0e ritten. Because o, t3is? t3e in$ut ar"ument ,or an O,T or IN O,T $arameter s3ould 0e somet3in" it3 an KlvalueK? suc3 as a varia0le li.e v in t3e e5am$le a0ove. + constant or a literal ar"ument s3ould not 0e $assed in ,or an O,TAIN O,T $arameter. IN Parameters *5am$le 4unnin" t3is statement in iSQLHPlus creates t3e RAI$E7$ALARD $rocedure. B3en invo.ed? RAI$E7$ALARD acce$ts t3e $arameter ,or t3e em$lo1ee ID and u$dates t3e em$lo1eeLs record it3 a salar1 increase o, 1- $ercent.

CREATE OR REPLACE PROCED,RE rai* 7*alary (p7id IN mploy *@ mploy 7idCTDPE) I$ BEGIN ,PDATE mploy * $ET *alary ; *alary F 0@01 :/ERE mploy 7id ; p7id; END rai* 7*alary; A (o invo.e a $rocedure in iSQLHPlus? use t3e EXEC,TE command. EXEC,TE rai* 7*alary (0GH) (o invo.e a $rocedure ,rom anot3er $rocedure? use a direct call. +t t3e location o, callin" t3e ne $rocedure? enter t3e $rocedure name and actual $arameters. rai* 7*alary (0GH); OUT Parameters *5am$le Dedit a scri$t ,ile em$9@uer1.s@l ,or ,ollo in" e5am$leF !reate a $rocedure it3 O,T $arameters to retrieve in,ormation a0out an em$lo1ee.

CREATE OR REPLACE PROCED,RE I% ry7 mp (p7id IN mp@ mpnoCTDPE. p7nam O,T mp@ nam CTDPE. p7*alary O,T mp@*alCTDPE. p7(omm O,T mp@(ommCTDPE) I$ BEGIN $ELECT nam . *al. (omm

DBMS Unit 4

Procedural SQL Fundamentals: Part II

INTO p7nam . p7*alary. p7(omm 8RO2 mp :/ERE mpno ; p7id; END I% ry7 mp; (3e $rocedure acce$ts a value 76%4 ,or em$lo1ee ID and retrieves t3e name? salar1? and commission $ercenta"e o, t3e em$lo1ee it3 ID 76%4 into t3e t3ree out$ut $arameters. $5L! $5L! $5L! $5L! 3ARIABLE '7nam 3ARC/AR-(0J) 3ARIABLE '7*al N,2BER(J) 3ARIABLE '7(omm N,2BER(<) EXEC I% ry7 mp (GHJ<. ='7nam . ='7*al. ='7(omm) *%(( **)%lly (ompl t d@

PLA$5L pro( d%r

$5L! PRINT '7nam '7*al '7(omm@ G7NA2E G7$AL G7CO22 """""""""""""""""""""""""""" 2ARTIN 0-J1 0<11 in" O,T Parameters 4un t3e SQL scri$t ,ile to "enerate and com$ile t3e source code. !reate 3ost varia0les in iSQLHPlus? usin" t3e ;+4I+BL* command. Invo.e t3e QU*4C9*MP $rocedure? su$$l1in" t3ese 3ost varia0les as t3e OU( $arameters. &ote t3e use o, t3e colon D:F to re,erence t3e 3ost varia0les in t3e *M*!U(* command. 4. (o vie t3e values $assed ,rom t3e $rocedure to t3e callin" environment? use t3e P4I&( command. Note: Passin" a constant or e5$ression as an actual $arameter to t3e OU( varia0le causes com$ilation errors. For e5am$le: EXEC,TE I% ry7 mp(0G0. ='7nam . rai* K011. ='7(omm) ;ie 1. /. #. causes a com$ilation error. IN OUT Parameters *5am$le +n IN O,T $arameter acts as an initialiGed varia0le. !reate a $rocedure it3 an IN O,T $arameter to acce$t a c3aracter strin" containin" 1- di"its and return a $3one num0er ,ormatted as D'--F 6##>-%7%.

DBMS Unit 4

Procedural SQL Fundamentals: Part II

1-

4un t3e statement to create t3e 8OR2AT7P/ONE $rocedure. CREATE OR REPLACE PROCED,RE )ormat7phon (p7phon 7no IN O,T 3ARC/AR-) I$ BEGIN p7phon 7no =; 4(4 ## $,B$TR(p7phon 7no.0.9) ## 4)4 ## $,B$TR(p7phon 7no.<.9) ## 4"4 ## $,B$TR(p7phon 7no.G); END )ormat7phon ; ;ie 1. /. #. 4. %. in" IN O,T Parameters !reate a 3ost varia0le? usin" t3e 3ARIABLE command. Po$ulate t3e 3ost varia0le it3 a value? usin" an anon1mous PL2SQL 0loc.. Invo.e t3e 8OR2AT7P/ONE $rocedure? su$$l1in" t3e 3ost varia0le as t3e IN O,T $arameter. &ote t3e use o, t3e colon D:F to re,erence t3e 3ost varia0le in t3e EXEC,TE command. (o vie t3e value $assed 0ac. to t3e callin" environment? use t3e PRINT command.

$5L! 3ARIABLE '7phon 7no 3ARC/AR-(0J) $5L! BEGIN ='7phon 7no =; 4L11H991JGJ4; 9 END; < A PLA$5L pro( d%r *%(( **)%lly (ompl t d@ $5L! PRINT '7phon 7no G7P/ONE7NO """""""""""""""""""""""""""""""" L11H991JGJ $5L! EXEC,TE )ormat7phon (='7phon 7no) PLA$5L pro( d%r *%(( **)%lly (ompl t d@ $5L! PRINT '7phon 7no G7P/ONE7NO """""""""""""""""""""""""""""""" (L11)H99"1JGJ DEFAULT Option for Parameters Cou can initialiGe I& $arameters to de,ault values. (3at a1? 1ou can $ass di,,erent

DBMS Unit 4

Procedural SQL Fundamentals: Part II

11

num0ers o, actual $arameters to a su0$ro"ram? acce$tin" or overridin" t3e de,ault values as 1ou $lease. Moreover? 1ou can add ne ,ormal $arameters it3out 3avin" to c3an"e ever1 call to t3e su0$ro"ram. Cou can assi"n de,ault values onl1 to $arameters o, t3e IN mode. O,T and IN O,T $arameters are not $ermitted to 3ave de,ault values. I, de,ault values are $assed to t3ese t1$es o, $arameters? 1ou "et t3e ,ollo in" com$ilation error: PLS>--/#-: O,T and IN O,T ,ormal $arameters ma1 not 3ave de,ault e5$ressions *5am$le:

CREATE OR REPLACE PROCED,RE add7d pt (p7no IN d pt@d ptnoCTDPE DE8A,LT J1. p7nam IN d pt@dnam CTDPE DE8A,LT 4%nBnoMn4. p7lo( IN d pt@lo(CTDPE DE8A,LT 4TAIPEI4) I$ BEGIN IN$ERT INTO d pt(d ptno. dnam . lo() 3AL,E$ (p7no. p7nam . p7lo(); END add7d pt; I, an actual $arameter is not $assed? t3e de,ault value o, its corres$ondin" ,ormal $arameter is used. *5am$les o, Passin" Parameters

BEGIN add7d pt; add7d pt (H1. 4TRAINING4. 4TAIC/,NG4); add7d pt (p7lo( ;! 4TAINAN4. p7nam ;!4ED,CATION4); add7d pt (p7lo( ;! 4/$INC/,4) ; END; A $ELECT d ptno. dnam . lo( 8RO2 d pt; (3e anon1mous 0loc. a0ove s3o s t3e di,,erent a1s t3e ADD7DEPT $rocedure can 0e invo.ed? and t3e out$ut o, eac3 a1 t3e $rocedure is invo.ed. &ote: +ll t3e $ositional $arameters s3ould $recede t3e named $arameters in a su0$ro"ram call. Ot3er ise? 1ou ill receive an error messa"e? as s3o n in t3e ,ollo in" e5am$le: $5L! EXEC,TE add7d pt(p7no;!H1. p7nam ;!4TRAINING4. 4TAIC/,NG4);

DBMS Unit 4

Procedural SQL Fundamentals: Part II

1/

BEGIN add7d pt(p7no;!H1. p7nam ;!4TRAINING4. 4TAIC/,NG4); END; F ERROR at lin 0= ORA"1HJJ1= lin 0. (ol%mn <H= PL$"1190-= a po*itional param t r a**o(iation may not )olloM a nam d a**o(iation ORA"1HJJ1= lin 0. (ol%mn G= PLA$5L= $tat m nt i'nor d Invoking Procedure Declaring Subprograms Cou can declare su0$ro"rams in an1 PL2SQL 0loc.. (3is is an alternative to creatin" t3e stand>alone $rocedure LOG7EXEC it3in LEA3E7E2P. For e5am$le? CREATE OR REPLACE PROCED,RE l aE 7 mp (p7id IN mploy *@ mploy 7idCTDPE) I$ PROCED,RE lo'7 + ( I$ BEGIN IN$ERT INTO lo'7ta&l (%* r7id. lo'7dat ) 3AL,E$ (,$ER. $D$DATE); END lo'7 + (; BEGIN DELETE 8RO2 mp :/ERE mpno ; p7id; lo'7 + (; END l aE 7 mp; Su0$ro"rams declared in t3is manner are called local su0$ro"rams Dor local modulesF. Because t3e1 are de,ined it3in a declaration section o, anot3er $ro"ram. (3e sco$e o, local su0$ro"rams is limited to t3e $arent Denclosin"F 0loc. in 3ic3 t3e1 are de,ined. (3is means t3at local su0$ro"rams cannot 0e called ,rom outside t3e 0loc. in 3ic3 t3e1 are declared. Declarin" local su0$ro"rams en3ances t3e clarit1 o, t3e code 01 assi"nin" a$$ro$riate 0usiness>rule identi,iers to 0loc.s o, code. &ote: Cou must declare t3e su0$ro"ram in t3e declaration section o, t3e 0loc.? and it must 0e t3e last item? a,ter all t3e ot3er $ro"ram items.

DBMS Unit 4

Procedural SQL Fundamentals: Part II

1#

For e5am$le? a varia0le declared a,ter t3e end o, t3e su0$ro"ram? 0e,ore t3e BEGIN o, t3e $rocedure? ill cause a com$ilation error. I, t3e code must 0e accessed 01 multi$le a$$lications? $lace t3e su0$ro"ram in a $ac.a"e or create a stand>alone su0$ro"ram it3 t3e code. Invoking a Procedure from an Anonymous PL/SQL Block For e5am$le? invo.e t3e RAI$E7$ALARD $rocedure ,rom an anon1mous PL2SQL 0loc.. Procedures are calla0le ,rom an1 tool or lan"ua"e t3at su$$orts PL2SQL. DECLARE E7id N,2BER =; 0H9; BEGIN rai* 7*alary(E7id); ""inEoB CO22IT; @@@ END;

pro( d%r

Invoking a Procedure from Anot er Procedure For e5am$le: CREATE OR REPLACE PROCED,RE pro( **7 mp* I$ C,R$OR mp7(%r*or I$ $ELECT mpno 8RO2 mp; BEGIN 8OR mp7r ( IN mp7(%r*or LOOP rai* 7*alary( mp7r (@ mpno); END LOOP; CO22IT; END pro( **7 mp*; (3is e5am$le s3o s 1ou 3o to invo.e a $rocedure ,rom anot3er stored $rocedure. (3e PROCE$$7E2P$ stored $rocedure uses a cursor to $rocess all t3e records in t3e E2P ta0le and $asses eac3 em$lo1eeLs ID to t3e RAI$E7$ALARD $rocedure? 3ic3 results in a 1- $ercent salar1 increase across t3e com$an1. !emoving Procedures Dro$ a $rocedure stored in t3e data0ase. $ynta+=

DBMS Unit 4

Procedural SQL Fundamentals: Part II

14

DROP PROCED,RE procedure_name ; E+ampl = DROP PROCED,RE raise_salary ; Issuin" roll0ac. does not 3ave an e,,ect a,ter e5ecutin" a data de,inition lan"ua"e DDDLF command suc3 as DROP PROCED,RE? 3ic3 commits an1 $endin" transactions.

Creating Functions Be can also rite ,unctions instead o, $rocedures. + ,unction is a named PL2SQL 0loc. t3at returns a value. + ,unction can 0e stored in t3e data0ase as a sc3ema o08ect ,or re$eated e5ecution. + ,unction is called as $art o, an e5$ression. In a ,unction declaration? e ,ollo t3e $arameter list 01 RET,RN and t3e t1$e o, t3e return value. (3e s1nta5 is: CREATE >OR REPLACE? 8,NCTION )%n(tion7nam >(param t r0 >mod 0? datatyp 0. param t r- >mod -? datatyp -. @ @ @)? RET,RN datatyp I$#A$ PLA$5L Blo(B; (3e REPLACE o$tion indicates t3at i, t3e ,unction e5ists? it ill 0e dro$$ed and re$laced it3 t3e ne version created 01 t3e statement. (3e RET,RN data t1$e must not include a siGe s$eci,ication. PL2SQL 0loc.s start it3 eit3er BEGIN or t3e declaration o, local varia0les and end it3 eit3er END or END )%n(tion7nam . (3ere must 0e at least one RET,RN D +pr **ionF statement. Cou cannot re,erence 3ost or 0ind varia0les in t3e PL2SQL 0loc. o, a stored ,unction. S1nta5 De,initions: function_name &ame o, t3e ,unction parameter &ame o, a PL2SQL varia0le 3ose value is $assed into t3e ,unction mode (3e t1$e o, t3e $arameterA onl1 I& $arameters s3ould 0e declared datatype Data t1$e o, t3e $arameter RETURN datatype Data t1$e o, t3e 4*(U4& value t3at must 0e out$ut 01 t3e ,unction PL/SQL block Procedural 0od1 t3at de,ines t3e action $er,ormed 01 t3e ,unction

DBMS Unit 4

Procedural SQL Fundamentals: Part II

1%

Develop Stored Functions (3e ,ollo in" are t3e 0asic ste$s 1ou use to develo$ a stored ,unction. (3e ne5t t o $a"es $rovide ,urt3er details a0out creatin" ,unctions. 1. Brite t3e s1nta5: *nter t3e code to create a ,unction in a te5t editor and save it as a SQL scri$t ,ile. /. !om$ile t3e code: Usin" iSQLHPlus? u$load and run t3e SQL scri$t ,ile. (3e source code is com$iled into P code. (3e ,unction is created. #. Invo.e t3e ,unction ,rom a PL2SQL 0loc.. 4eturnin" a ;alue +dd a RET,RN clause it3 t3e data t1$e in t3e 3eader o, t3e ,unction. Include one RET,RN statement in t3e e5ecuta0le section. *5am$le: "et9salar1.s@l CREATE OR REPLACE 8,NCTION ' t7*al (p7id IN mp@ mpnoCTDPE) RET,RN N,2BER I$ E7*alary mp@*alCTDPE =;1; BEGIN $ELECT *al INTO E7*alary 8RO2 mp :/ERE mpno ; p7id; RET,RN E7*alary; END ' t7*al; xecuting Functions *5ecution a ,unction ma1 acce$t one or man1 $arameters? 0ut must return a sin"le value. Invo.e a ,unction as $art o, a PL2SQL e5$ression. !reate a varia0le to 3old t3e returned value. *5ecute t3e ,unction. (3e varia0le ill 0e $o$ulated 01 t3e value returned t3rou"3 a RET,RN statement. *5am$le: Load and run t3e "et9salar1.s@l ,ile to create t3e ,unction $5L! 3ARIABLE '7*alary N,2BER $5L! EXEC ='7*alary =; ' t7*al(GL9N) PLA$5L pro( d%r *%(( **)%lly (ompl t d@ $5L! PRINT '7*alary G7$ALARD

DBMS Unit 4

Procedural SQL Fundamentals: Part II

16

"""""""""" J111 Invoking "unctions in SQL #$pressions *5am$le: create a ,unction ta5 t3at is invo.ed ,rom a $ELECT statement. (3e ,unction acce$ts a N,2BER $arameter and returns t3e ta5 a,ter multi$l1in" t3e $arameter value it3 -.-'. $5L! 9 < J H G CREATE OR REPLACE 8,NCTION ta+(p7Eal% RET,RN N,2BER I$ BEGIN RET,RN (p7Eal% F 1@1L); END ta+; A IN N,2BER)

*5ecute: $5L! $ELECT mpno. nam . *al. ta+(*al) - 8RO2 mp 9 :/ERE d ptno ; 01; E2PNO """""""""" GGLGL9N GN9< 0111 ENA2E $AL TAX($AL) """""""""" """""""""" """""""""" CLARO -<J1 0NH OING J111 <11 2ILLER 0911 01< T7E7$CTT -111 0H1

Usa"e o, User>De,ined Functions Select list o, a S*L*!( command !ondition o, t3e B=*4* and =+;I&< clauses CONNECT BD? $TART :IT/? ORDER BD? and GRO,P BD clauses 3AL,E$ clause o, t3e IN$ERT command $ET clause o, t3e ,PDATE command *5am$le: Find em$lo1ees 3ose ta5 is more t3an t3e ma5imum ta5 in t3e de$artment Dde$tno I #-F.

$5L! $ELECT mpno. ta+(*al) - 8RO2 mp 9 :/ERE ta+(*al)!($ELECT 2AX(ta+(*al)) < 8RO2 mp :/ERE d ptno ; 91)

DBMS Unit 4

Procedural SQL Fundamentals: Part II

17

ORDER BD ta+(*al) DE$C;

!estrictions on %alling "unctions from SQL #$pressions B3en called ,rom a $ELECT statement or a $aralleliGed ,PDATE or DELETE statement? t3e ,unction cannot modi,1 an1 data0ase ta0les. B3en called ,rom an ,PDATE? or DELETE statement? t3e ,unction cannot @uer1 or modi,1 an1 data0ase ta0les modi,ied 01 t3at statement. B3en called ,rom a $ELECT? IN$ERT? ,PDATE? or DELETE statement? t3e ,unction cannot e5ecute SQL transaction control statements Dsuc3 as CO22ITF? session control statements Dsuc3 as $ET ROLEF? or s1stem control statements Dsuc3 as ALTER $D$TE2F. +lso? it cannot e5ecute DDL statements Dsuc3 as CREATEF 0ecause t3e1 are ,ollo ed 01 an automatic commit. (3e ,unction cannot call anot3er su0$ro"ram t3at 0rea.s one o, t3e a0ove restrictions. !onsider t3e ,ollo in" e5am$le 3ere t3e ,unction 5,ERD7CALL7$5L @ueries t3e $AL column o, t3e E2P ta0le:

CREATE OR REPLACE 8,NCTION I% ry7(all7*Il(a N,2BER) RET,RN N,2BER I$ * N,2BER; BEGIN $ELECT *al INTO * 8RO2 mp :/ERE mpno ; GL9N; RET,RN (* K a); END; A (3e a0ove ,unction? 3en invo.ed ,rom t3e ,ollo in" ,PDATE statement? returns t3e error messa"e. $5L! ,PDATE mp $ET *al ; I% ry7(all7*Il(GGLL) - :/ERE mpno ; GL9N; ,PDATE mp $ET *al ; I% ry7(all7*Il(GGLL) F ERROR at lin 0= ORA"1<1N0= ta&l $NO:BALL@E2P i* m%tatin'. tri'' rA)%n(tion may not * it ORA"1HJ0-= at P$NO:BALL@5,ERD7CALL7$5LP. lin H

DBMS Unit 4

Procedural SQL Fundamentals: Part II

1'

!emoving "unctions Dro$ a stored ,unction. $ynta+= DROP 8,NCTION function_name; E+ampl = DROP 8,NCTION get_sal; +ll t3e $rivile"es "ranted on a ,unction are revo.ed 3en t3e ,unction is dro$$ed. (3e CREATE OR REPLACE s1nta5 is e@uivalent to dro$$in" a ,unction and recreatin" it. Privile"es "ranted on t3e ,unction remain t3e same 3en t3is s1nta5 is used. Comparing Procedures and Functions Procedures *5ecute as a PL2SQL statement Do not contain RET,RN clause in t3e 3eader !an return none? one? or man1 values !an contain a RET,RN statement Managing Stored PL/SQL Ob ects Stored Information <eneral Source code Parameters P>code !om$ile errors 4un>time de0u" in,ormation Description O08ect in,ormation (e5t o, t3e $rocedure Mode: INA O,TA IN O,T? datat1$e !om$iled o08ect code PL2SQL s1nta5 errors User>s$eci,ied de0u" varia0les and messa"es Access Method (3e ,$ER7OBQECT$ data dictionar1 vie (3e ,$ER7$O,RCE data dictionar1 vie iSQLHPlus: DE$CRIBE command &ot accessi0le (3e ,$ER7ERROR$ data dictionar1 vie iSQLHPlus: $/O: ERROR$ command (3e DB2$7O,TP,T Oracle>su$$lied $ac.a"e "unctions Invo.e as $art o, an e5$ression Must contain a RET,RN clause in t3e 3eader Must return a sin"le value Must contain at least one RET,RN statement

USER_OBJECTS Data Dictionary !iew Column OB:*!(9&+M* OBQECT7ID OBQECT7TDPE CREATED &ame o, t3e o08ect Internal identi,ier ,or t3e o08ect (1$e o, o08ect? ,or e5am$le? TABLE. PROCED,RE. 8,NCTION. PACOAGE. PACOAGE. BODD. TRIGGER Date 3en t3e o08ect as created Column Description

DBMS Unit 4

Procedural SQL Fundamentals: Part II

1)

LA$T7DDL7TI2E TI2E$TA2P $TAT,$

Date 3en t3e o08ect as last modi,ied Date and time 3en t3e o08ect as last recom$iled 3ALID or IN3ALID

USER_SOURCE Data Dictionary !iew Column &+M* TDPE LINE TEXT &ame o, t3e o08ect (1$e o, o08ect? ,or e5am$le? P4O!*DU4*? FU&!(IO&? P+!N+<*? P+!N+<* BODC Line num0er o, t3e source code Column Description

List t3e !ode o, Procedures and Functions

$ELECT t +t 8RO2 %* r7*o%r( :/ERE nam ; 45,ERD7E2PLODEE4 ORDER BD lin ; USER_ERRORS Data Dictionary !iew O0tainin" !om$ile *rrors Column &+M* (CP* $E5,ENCE LINE PO$ITION TEXT &ame o, t3e o08ect (1$e o, o08ect? ,or e5am$le? PROCED,RE. 8,NCTION. PACOAGE. PACOAGE BODD. TRIGGER Se@uence num0er? ,or orderin" Line num0er o, t3e source code at 3ic3 t3e error occurs Position in t3e line at 3ic3 t3e error occurs (e5t o, t3e error messa"e Column Description

*5am$le: List !om$ilation *rrors 01 Usin" ,$ER7ERROR$

$ELECT lin ## 4A4 ## po*ition PO$. t +t 8RO2 %* r7 rror* :/ERE nam ; 4LOG7EXEC4 ORDER BD lin ; (3e ,$ER7ERROR$ data dictionar1 vie stores all t3e com$ilation errors "enerated $reviousl1 3ile creatin" su0$ro"rams. *5am$le: List !om$ilation *rrors 01 Usin" $/O: ERROR$ Usin" t3e $/O: ERROR$ command? 1ou can vie onl1 t3e com$ilation errors t3at are "enerated 01 t3e latest statement t3at is used to create a su0$ro"ram.

$/O: ERROR$ PROCED,RE lo'7 + (

DBMS Unit 4

Procedural SQL Fundamentals: Part II

/-

(3e s1nta5 o, $/O: ERROR$ is: $/O: ERROR$ >R8,NCTION#PROCED,RE#PACOAGE#PACOAGE BODD# TRIGGER#3IE:S >*(h ma@?nam ? Summary ame US*49OB:*!(S ,$ER7$O,RCE DE$CRIBE ,$ER7ERROR$ $/O: ERROR$ DB2$7O,TP,T GRANT Data Dictionary !ie" or Command Data dictionar1 vie Data dictionar1 vie iSQLHPlus command Data dictionar1 vie iSQLHPlus command Oracle>su$$lied $ac.a"e iSQL command Description Provides "eneral in,ormation a0out t3e o08ect Provides t3e te5t o, t3e o08ect? Dt3at is? t3e PL2SQL 0loc.F Provides t3e declaration o, t3e o08ect S3o s com$ilation errors S3o s com$ilation errors? $er $rocedure or ,unction Provides user>s$eci,ied de0u""in"? "ivin" varia0le values and messa"es Provides t3e securit1 $rivile"es ,or t3e o ner 3o creates t3e $rocedure and t3e user 3o runs it? ena0lin" t3em to $er,orm t3eir res$ective o$erations

Package Overview o" Packages <rou$ lo"icall1 related PL2SQL t1$es? items? and su0$ro"rams For e5am$le? a =uman 4esources $ac.a"e can contain 3irin" and ,irin" $rocedures? commission and 0onus ,unctions? and ta5 e5em$tion varia0les. !onsist o, t o $arts stored se$aratel1 in t3e data0ase: S$eci,ication t3e inter,ace to 1our a$$lications. It declares t3e t1$es? varia0les? constants? e5ce$tions? cursors? and su0$ro"rams availa0le ,or use. (3e $ac.a"e s$eci,ication ma1 also include P4+<M+s? 3ic3 are directives to t3e com$iler. Bod1 ,ull1 de,ines cursors and su0$ro"rams? and so im$lements t3e s$eci,ication. !annot 0e invo.ed? $arameteriGed? or nested (3e ,ormat o, a $ac.a"e is similar to t3at o, a su0$ro"ram. Once ritten and

DBMS Unit 4

Procedural SQL Fundamentals: Part II

/1

com$iled? t3e contents can 0e s3ared 01 man1 a$$lications. +llo t3e Oracle server to read multi$le o08ects into memor1 at once Later calls to constructs in t3e same $ac.a"e re@uire no dis. in$ut2out$ut DI2OF. !om$onents o, a Pac.a"e

Cou create a $ac.a"e in t o $arts: ,irst t3e $ac.a"e s$eci,ication? and t3en t3e $ac.a"e 0od1. Pu0lic $ac.a"e constructs are t3ose t3at are declared in t3e $ac.a"e s$eci,ication and de,ined in t3e $ac.a"e 0od1. Private $ac.a"e constructs are t3ose t3at are de,ined solel1 it3in t3e $ac.a"e 0od1. Scope o" the Construct Pu0lic Description !an 0e re,erenced ,rom an1 Oracle server environment Placement within the Package Declared it3in t3e $ac.a"e s$eci,ication and ma1 0e de,ined it3in t3e $ac.a"e 0od1

Private

!an 0e re,erenced onl1 01 Declared and de,ined it3in t3e ot3er constructs 3ic3 are $art $ac.a"e 0od1 o, t3e same $ac.a"e

&ote: (3e Oracle server stores t3e s$eci,ication and 0od1 o, a $ac.a"e se$aratel1 in t3e data0ase. (3is ena0les 1ou to c3an"e t3e de,inition o, a $ro"ram construct in t3e $ac.a"e 0od1 it3out causin" t3e Oracle server to invalidate ot3er sc3ema o08ects

DBMS Unit 4

Procedural SQL Fundamentals: Part II

//

t3at call or re,erence t3e $ro"ram construct. 4e,erencin" Pac.a"e O08ects + varia0le de,ined it3in a su0$ro"ram t3at is not visi0le to e5ternal users. Private Dlocal to t3e $ac.a"eF varia0le: Cou can de,ine varia0les in a $ac.a"e 0od1. Onl1 ot3er o08ects in t3e same $ac.a"e can access t3ese varia0les. (3e1 are not visi0le to an1 su0$ro"rams or o08ects outside o, t3e $ac.a"e. + varia0le or su0$ro"ram t3at can 0e re,erenced Dand c3an"edF outside t3e $ac.a"e and is visi0le to e5ternal users. <lo0al $ac.a"e items must 0e declared in t3e $ac.a"e s$eci,ication.

!isi#ility o" the Construct Description Local

<lo0al

Creating Packages (3ree 0asic ste$s to Develo$ a Pac.a"e 1. Brite t3e te5t o, t3e CREATE PACOAGE statement it3in a SQL scri$t ,ile to create t3e $ac.a"e s$eci,ication and run t3e scri$t ,ile. (3e source code is com$iled into P code and is stored it3in t3e data dictionar1. /. Brite t3e te5t o, t3e CREATE PACOAGE BODD statement it3in a SQL scri$t ,ile to create t3e $ac.a"e 0od1 and run t3e scri$t ,ile. (3e source code is com$iled into P code and is also stored it3in t3e data dictionar1. #. Invo.e an1 $u0lic construct it3in t3e $ac.a"e ,rom an Oracle server environment. %reating t e Package Specification S1nta5: CREATE >OR REPLACE? PACOAGE package_name I$#A$ public type and item declarations subprogram specifications END pa(Ba' 7nam ; S1nta5 De,inition Parameter package_name Description &ame t3e $ac.a"e

public type and item Declare varia0les? constants? cursors? e5ce$tions? or t1$es declarations subprogram specifications Declare t3e PL2SQL su0$ro"rams

S$eci,1 t3e REPLACE o$tion 3en t3e $ac.a"e s$eci,ication alread1 e5ists.

DBMS Unit 4

Procedural SQL Fundamentals: Part II

/#

InitialiGe a varia0le it3 a constant value or ,ormula it3in t3e declaration? i, re@uiredA ot3er ise? t3e varia0le is initialiGed im$licitl1 to N,LL. Declarin" Pu0lic !onstructs In t3e $ac.a"e s$eci,ication? 1ou declare $u0lic varia0les? $u0lic $rocedures? and $u0lic ,unctions. (3e $u0lic $rocedures or ,unctions are routines t3at can 0e invo.ed re$eatedl1 01 ot3er constructs in t3e same $ac.a"e or ,rom outside t3e $ac.a"e. For e5am$le 0elo ? G7CO22 is a $u0lic D"lo0alF varia0le? and RE$ET7CO22 is a $u0lic $rocedure t3at is im$lemented in t3e $ac.a"e 0od1..

CREATE OR REPLACE PACOAGE (omm7pa(Ba' I$ '7(omm N,2BER =; 1@01; ""initialiT d to 1@01 PROCED,RE r * t7(omm (p7(omm IN N,2BER); END (omm7pa(Ba' ; %reating t e Package Body S1nta5: CREATE >OR REPLACE? PACOAGE BODD package_name I$#A$ pri ate type and item declarations subprogram bodies END pa(Ba' 7nam ; In t3e s1nta5: Parameter $ac.a"e9name $rivate t1$e and item declarations su0$ro"ram 0odies Description Is t3e name o, t3e $ac.a"e Declares varia0les? constants? cursors? e5ce$tions? or t1$es De,ines t3e PL2SQL su0$ro"rams? $u0lic and $rivate

De,ine all $u0lic and $rivate $rocedures and ,unctions in t3e $ac.a"e 0od1. (3e REPLACE o$tion dro$s and recreates t3e $ac.a"e 0od1. S$eci,1 t3e t3e o$tion 3en t3e $ac.a"e 0od1 alread1 e5ists. Identi,iers de,ined onl1 in t3e $ac.a"e 0od1 are $rivate constructs. (3ese are not visi0le outside t3e $ac.a"e 0od1. +ll $rivate constructs must 0e declared 0e,ore t3e1 are used in t3e $u0lic constructs. !reate a Pac.a"e Bod1 *5am$le Dcomm.9$ac..s@lF

CREATE OR REPLACE PACOAGE BODD (omm7pa(Ba' I$

DBMS Unit 4

Procedural SQL Fundamentals: Part II

/4

8,NCTION Ealidat 7(omm (p7(omm IN N,2BER) RET,RN BOOLEAN I$ E7ma+7(omm N,2BER; BEGIN $ELECT 2AX((ommi**ion7p(t) INTO E7ma+7(omm 8RO2 mploy *; I8 p7(omm ! E7ma+7(omm T/EN RET,RN(8AL$E); EL$E RET,RN(TR,E); END I8; END Ealidat 7(omm; PROCED,RE r * t7(omm (p7(omm IN N,2BER) I$ BEGIN I8 Ealidat 7(omm(p7(omm) T/EN '7(omm=;p7(omm; ""r * t 'lo&al Earia&l EL$E RAI$E7APPLICATION7ERROR("-1-01.4InEalid (ommi**ion4); END I8; END r * t7(omm; END (omm7pa(Ba' ;

DBMS Unit 4

Procedural SQL Fundamentals: Part II

/%

1 is a $u0lic D"lo0alF varia0le / is a $u0lic $rocedure # is a $rivate ,unction Invoking Package Constructs *5am$le 1: Invo.e a ,unction ,rom a $rocedure it3in t3e same $ac.a"e. CREATE OR REPLACE PACOAGE BODD (omm7pa(Ba' I$ @ @ @ PROCED,RE r * t7(omm (p7(omm IN N,2BER) I$ BEGIN I8 Ealidat 7(omm(p7(omm) T/EN '7(omm =; p7(omm; EL$E RAI$E7APPLICATION7ERROR("-1-01. 4InEalid (ommi**ion4); END I8; END r * t7(omm; END (omm7pa(Ba' ; !all t3e 3ALIDATE7CO22 ,unction ,rom t3e RE$ET7CO22 $rocedure. Bot3 su0$ro"rams are in t3e CO227PACOAGE $ac.a"e. *5am$le /: Invo.e a $ac.a"e $rocedure ,rom iSQLHPlus. !all t3e RE$ET7CO22 $rocedure ,rom iSQLHPlus? ma.in" t3e $revailin" commission -.1% ,or t3e user session. *5am$le #: Invo.e a $ac.a"e $rocedure in a di,,erent sc3ema. !all t3e RE$ET7CO22 $rocedure t3at is located in t3e $COTT sc3ema ,rom iSQLHPlus? ma.in" t3e $revailin" commission -.1% ,or t3e user session. *5am$le 4: Invo.e a $ac.a"e $rocedure in a remote data0ase. !all t3e RE$ET7CO22 $rocedure t3at is located in a remote data0ase t3at is determined 01 t3e data0ase lin. named ND ,rom iSQLHPlus? ma.in" t3e $revailin" commission -.1% ,or t3e user session. Declaring a Bodiless Package *5am$le: a $ac.a"e s$eci,ication containin" several conversion rates is de,ined. +ll t3e

EXEC,TE (omm7pa(Ba' @r * t7(omm(1@0J)

EXEC,TE *(ott@(omm7pa(Ba' @r * t7(omm(1@0J)

EXEC,TE (omm7pa(Ba' @r * t7(ommUny(1@0J)

DBMS Unit 4

Procedural SQL Fundamentals: Part II

/6

"lo0al identi,iers are declared as constants. CREATE OR REPLACE PACOAGE 'lo&al7(on*t* I$ mil 7-7Bilo CON$TANT N,2BER =; 0@H1N9; Bilo7-7mil CON$TANT N,2BER =; 1@H-0<; yard7-7m t r CON$TANT N,2BER =; 1@N0<<; m t r7-7yard CON$TANT N,2BER =; 0@1N9H; END 'lo&al7(on*t*; A EXEC,TE DB2$7O,TP,T@P,T7LINE(4-1 mil * ; 4##-1F 'lo&al7(on*t*@mil 7-7Bilo##4 Bm4) Cou can declare $u0lic D"lo0alF varia0les t3at e5ist ,or t3e duration o, t3e user session. Cou can create a $ac.a"e s$eci,ication t3at does not need a $ac.a"e 0od1. + $ac.a"e 0od1 is not re@uired to su$$ort t3is $ac.a"e s$eci,ication 0ecause im$lementation details are not re@uired ,or an1 o, t3e constructs o, t3e $ac.a"e s$eci,ication. 4e,erencin" a Pu0lic ;aria0le ,rom a Stand>+lone Procedure *5am$le:

CREATE OR REPLACE PROCED,RE m t r7to7yard (p7m t r IN N,2BER. p7yard O,T N,2BER) I$ BEGIN p7yard =; p7m t r F 'lo&al7(on*t*@m t r7-7yard; END m t r7to7yard; A 3ARIABLE yard N,2BER EXEC,TE m t r7to7yard (0. =yard) PRINT yard Use t3e 2ETER7TO7DARD $rocedure to convert meters to 1ards? usin" t3e conversion rate $ac.a"ed in GLOBAL7CON$T$. B3en 1ou re,erence a varia0le? cursor? constant? or e5ce$tion ,rom outside t3e $ac.a"e? 1ou must @uali,1 its name it3 t3e name o, t3e $ac.a"e. $emoving Packages (o remove t3e $ac.a"e s$eci,ication and t3e 0od1? use t3e ,ollo in" s1nta5: DROP PACOAGE pa(Ba' 7nam ; (o remove t3e $ac.a"e 0od1? use t3e ,ollo in" s1nta5:

DBMS Unit 4

Procedural SQL Fundamentals: Part II

/7

DROP PACOAGE BODD pa(Ba' 7nam ; %uidelines "or Developing Packages !onstruct $ac.a"es ,or "eneral use. De,ine t3e $ac.a"e s$eci,ication 0e,ore t3e 0od1. (3e $ac.a"e s$eci,ication s3ould contain onl1 t3ose constructs t3at 1ou ant to 0e $u0lic. Place items in t3e declaration $art o, t3e $ac.a"e 0od1 3en 1ou must maintain t3em t3rou"3out a session or across transactions. !3an"es to t3e $ac.a"e s$eci,ication re@uire recom$ilation o, eac3 re,erencin" su0$ro"ram. (3e $ac.a"e s$eci,ication s3ould contain as ,e constructs as $ossi0le. Overload: Local or $ac.a"ed su0$ro"rams can 0e overloaded. DCou cannot overload stand>alone su0$ro"rams.F *na0les 1ou to use t3e same name ,or di,,erent su0$ro"rams inside a PL2SQL 0loc.? a su0$ro"ram? or a $ac.a"e 4e@uires t3e ,ormal $arameters o, t3e su0$ro"rams to di,,er in num0er? order? or data t1$e ,amil1 *na0les 1ou to 0uild more ,le5i0ilit1 0ecause a user or a$$lication is not restricted 01 t3e s$eci,ic data t1$e or num0er o, ,ormal $arameters Cou must declare identi,iers 0e,ore re,erencin" t3em? i.e.? PL2SQL does not allo ,or ard re,erences. (3ere,ore? a su0$ro"ram must 0e declared 0e,ore callin" it. !ommand Summar1: Command #ask CREATE >OR REPLACE? PACOAGE !reate Dor modi,1F an e5istin" $ac.a"e s$eci,ication CREATE >OR REPLACE? PACOAGE !reate Dor modi,1F an e5istin" $ac.a"e 0od1 BODD DROP PACOAGE DROP PACOAGE BODD 4emove 0ot3 t3e $ac.a"e s$eci,ication and t3e $ac.a"e 0od1 4emove t3e $ac.a"e 0od1 onl1

Oracle Supplied Packages Brite d1namic SQL statements usin" DB2$7$5L and EXEC,TE I22EDIATE SQL statement contains varia0les t3at can c3an"e durin" runtime SQL statement is it3 $lace3olders and is stored as a c3aracter strin" +$$lication o, some Oracle server>su$$lied $ac.a"es: DB2$7DDL

DBMS Unit 4

Procedural SQL Fundamentals: Part II

/'

DB2$7QOB DB2$7O,TP,T ,TL78ILE ,TL7/TTP and ,TL7TCP Ste$s to Process SQL Statements +ll SQL statements 3ave to "o t3rou"3 various sta"es. Some sta"es ma1 0e s.i$$ed. Parse: *ver1 SQL statement must 0e $arsed. Parsin" t3e statement includes c3ec.in" t3e statementEs s1nta5 and validatin" t3e statement? ensurin" t3at all re,erences to o08ects are correct? and ensurin" t3at t3e relevant $rivile"es to t3ose o08ects e5ist. Bind: +,ter $arsin"? t3e Oracle server .no s t3e meanin" o, t3e Oracle statement 0ut still ma1 not 3ave enou"3 in,ormation to e5ecute t3e statement. (3e Oracle server ma1 need values ,or an1 0ind varia0le in t3e statement. (3e $rocess o, o0tainin" t3ese values is called 0indin" varia0les. *5ecute: +t t3is $oint? t3e Oracle server 3as all necessar1 in,ormation and resources? and t3e statement is e5ecuted. Fetc3: In t3e ,etc3 sta"e? ro s are selected and ordered Di, re@uested 01 t3e @uer1F? and eac3 successive ,etc3 retrieves anot3er ro o, t3e result? until t3e last ro 3as 0een ,etc3ed. Cou can ,etc3 @ueries? 0ut not t3e DML statements.

&sing t e DBMS_SQL Package (3e DB2$7$5L $ac.a"e is used to rite d1namic SQL in stored $rocedures and to $arse DDL statements. $unction or Procedure OP*&9!U4SO4 PAR$E Description O$ens a ne cursor and assi"ns a cursor ID num0er Parses t3e DDL or DML statement: t3at is? c3ec.s t3e statementLs s1nta5 and associates it it3 t3e o$ened cursor DDDL statements are immediatel1 e5ecuted 3en $arsedF Binds t3e "iven value to t3e varia0le identi,ied 01 its name in t3e $arsed statement in t3e "iven cursor *5ecutes t3e SQL statement and returns t3e num0er o, ro s $rocessed 4etrieves a ro ,or t3e s$eci,ied cursor D,or multi$le ro s? call in a loo$F

BIND73ARIABLE EXEC,TE 8ETC/7RO:$ CLO$E7C,R$OR

!loses t3e s$eci,ied cursor *5am$le: (3e ta0le name is $assed into t3e DELETE7ALL7RO:$ $rocedure 01 usin" an I& $arameter. (3e $rocedure uses d1namic SQL to delete ro s ,rom t3e s$eci,ied ta0le.

DBMS Unit 4

Procedural SQL Fundamentals: Part II

/)

(3e num0ers o, ro s t3at are deleted as a result o, t3e success,ul e5ecution o, t3e d1namic SQL are $assed to t3e callin" environment t3rou"3 an O,T $arameter. CREATE OR REPLACE PROCED,RE d l t 7all7roM* (p7ta&7nam IN 3ARC/AR-. p7roM*7d l O,T N,2BER) I$ (%r*or7nam INTEGER; BEGIN (%r*or7nam =; DB2$7$5L@OPEN7C,R$OR; DB2$7$5L@PAR$E((%r*or7nam . 4DELETE 8RO2 4##p7ta&7nam . DB2$7$5L@NATI3E ); p7roM*7d l =; DB2$7$5L@EXEC,TE ((%r*or7nam ); DB2$7$5L@CLO$E7C,R$OR((%r*or7nam ); END; Use d1namic SQL to delete ro s 3ARIABLE d l t d N,2BER EXEC,TE d l t 7all7roM*(4 mploy PRINT d l t d *4. =d l t d)

Use OPEN7C,R$OR to esta0lis3 an area in memor1 to $rocess a SQL statement. Use PAR$E to esta0lis3 t3e validit1 o, t3e SQL statement. Use t3e EXEC,TE ,unction to run t3e SQL statement. (3is ,unction returns t3e num0er o, ro $rocessed. Use CLO$E7C,R$OR to close t3e cursor. Use t3e EXEC,TE I22EDIATE statement ,or native d1namic SQL it3 0etter $er,ormance.

$ynta+= EXEC,TE I22EDIATE dynami(7*trin' >INTO Rd )in 7Earia&l >. d )in 7Earia&l ? @@@ # r (ordS? >,$ING >IN#O,T#IN O,T? &ind7ar'%m nt >. >IN#O,T#IN O,T? &ind7ar'%m nt? @@@ ?; De,inition: Parameter d1namic9strin" Description + strin" e5$ression t3at re$resents a d1namic SQL statement D it3out terminatorF or a PL2SQL 0loc. D it3 terminatorF

d )in 7Earia&l + varia0le t3at stores t3e selected column value record + user>de,ined or CRO:TDPE record t3at stores a selected ro

DBMS Unit 4

Procedural SQL Fundamentals: Part II

#-

&ind7ar'%m nt

+n e5$ression 3ose value is $assed to t3e d1namic SQL statement or PL2SQL 0loc.

INTO is used ,or sin"le>ro @ueries and s$eci,ies t3e varia0les or records into 3ic3 column values are retrieved. But? 1ou must use OPEN"8OR? 8ETC/? and CLO$E ,or a multiro @uer1. ,$ING is used to 3old all 0ind ar"uments. (3e de,ault $arameter mode is IN. *5am$le: D1namic SQL Usin" EXEC,TE I22EDIATE

CREATE PROCED,RE d l7roM* (p7ta&l 7nam IN 3ARC/AR-. p7roM*7d ld O,T N,2BER) I$ BEGIN EXEC,TE I22EDIATE 4d l t )rom 4##p7ta&l 7nam ; p7roM*7d ld =; $5LCRO:CO,NT; END; D1namic SQL Usin" EXEC,TE I22EDIATE 3ARIABLE d l t d N,2BER EXEC,TE d l7roM*(4t *t7 mploy PRINT d l t d *4.=d l t d)

&sing t e DB'S(DDL Package (3is $ac.a"e $rovides access to some SQL DDL statements? 3ic3 1ou can use in PL2SQL $ro"rams. DB2$7DDL is not allo ed in tri""ers? in $rocedures called ,rom Forms Builder? or in remote sessions. (3is $ac.a"e runs it3 t3e $rivile"es o, callin" user? rat3er t3an t3e $ac.a"e o ner $D$. Includes some $rocedures: ALTER7CO2PILE (o&6 (t7typ . oMn r. o&6 (t7nam )

E+ampl = DB2$7DDL@ALTER7CO2PILE(4PROCED,RE4.4A7,$ER4.45,ERD7E2P4) ANALDVE7OBQECT (o&6 (t7typ . oMn r. nam . m thod) E+ampl = DB2$7DDL@ANALDVE7OBQECT(4TABLE4.4A7,$ER4.4QOB$4.4CO2P,TE4) &sing DB'S()OB for Sc eduling DBMS9:OB *na0les t3e sc3edulin" and e5ecution o, PL2SQL $ro"rams: Su0mittin" 8o0s

DBMS Unit 4

Procedural SQL Fundamentals: Part II

#1

*5ecutin" 8o0s !3an"in" e5ecution $arameters o, 8o0s 4emovin" 8o0s Sus$endin" :o0s +vaila0le su0$ro"rams: Description Su0mits a 8o0 to t3e 8o0 @ueue 4emoves a s$eci,ied 8o0 ,rom t3e 8o0 @ueue +lters a s$eci,ied 8o0 t3at 3as alread1 0een su0mitted to t3e 8o0 @ueue D1ou can alter t3e 8o0 descri$tion? t3e time at 3ic3 t3e 8o0 ill 0e run? or t3e interval 0et een e5ecutions o, t3e 8o0F +lters t3e 8o0 descri$tion ,or a s$eci,ied 8o0

Subpro%ram SUBMI( RE2O3E C/ANGE

:/AT

NEXT7DATE +lters t3e ne5t e5ecution time ,or a s$eci,ied 8o0 INTER3AL +lters t3e interval 0et een e5ecutions ,or a s$eci,ied 8o0 BROOEN R,N Disa0les 8o0 e5ecution Di, a 8o0 is mar.ed as 0ro.en? t3e Oracle server does not attem$t to e5ecute itF

Forces a s$eci,ied 8o0 to run DB2$7QOB@$,B2IT. (3e $rocedure adds a ne 8o0 to t3e 8o0 @ueue. It acce$ts ,ive $arameters and returns t3e num0er o, a 8o0 su0mitted t3rou"3 t3e OU( $arameter :OB.

Parameter Mode #ype Default Description QOB O,T BI&+4C9I&(*<*4 Uni@ue identi,ier o, t3e 8o0 :/AT IN 3ARC/ARPL2SQL code to e5ecute as a 8o0 NEXT7DATE IN DATE S1sdate &e5t e5ecution date o, t3e 8o0 INTER3AL IN NO7PAR$E IN 3ARC/ARBOOLEAN &ull False Date ,unction to com$ute t3e ne5t e5ecution date o, a 8o0 Boolean ,la" t3at indicates 3et3er to $arse t3e 8o0 at 8o0 su0mission Dt3e de,ault is ,alseF

*5am$le: Use DB2$7QOB@$,B2IT to $lace a 8o0 to 0e e5ecuted in t3e 8o0 @ueue. (3is 8o0 is su0mitted to run ever1 da1 at midni"3t. 3ARIABLE 6o&no N,2BER BEGIN DB2$7QOB@$,B2IT ( 6o& ;! =6o&no. Mhat ;! 4O3ER7PACO@ADD7DEPT(44ED,CATION44.-G01);4. n +t7dat ;! TR,NC($D$DATE K 0). int rEal ;! 4TR,NC($D$DATE K 0)4

DBMS Unit 4

Procedural SQL Fundamentals: Part II

#/

); CO22IT; END; A P4I&( 8o0no (3e 0loc. o, code su0mits t3e ADD7DEPT $rocedure o, t3e O3ER7PACO $ac.a"e to t3e 8o0 @ueue. (3e 8o0 num0er is returned t3rou"3 t3e QOB $arameter. (3e :/AT $arameter must 0e enclosed in sin"le @uotation mar.s and must include a semicolon at t3e end o, t3e te5t strin". (3e transactions in t3e su0mitted 8o0 are not committed until eit3er CO22IT is issued? or DB2$7QOB@R,N is e5ecuted to run t3e 8o0. CO22IT in t3e slide

commits t3e transaction. !3an"in" :o0 !3aracteristics DB2$7QOB@C/ANGE: !3an"es t3e :/AT? NEXT7DATE? and INTER3AL $arameters DB2$7QOB@INTER3AL: !3an"es t3e INTER3AL $arameter DB2$7QOB@NEXT7DATE: !3an"es t3e ne5t e5ecution date DB2$7QOB@:/AT: !3an"es t3e B=+( $arameter *5am$le (3e ,ollo in" code c3an"es 8o0 num0er 1 to e5ecute on t3e ,ollo in" da1 at 6:-- a.m. and ever1 ,our ours a,ter t3at.

BEGIN DB2$7QOB@C/ANGE(0. N,LL. TR,NC($D$DATEK0)KHA-<. W$D$DATEK<A-<4); END; &ote: *ac3 o, t3ese $rocedures can 0e e5ecuted on 8o0s o ned 01 t3e username to 3ic3 t3e session s connected. I, t3e $arameter 3at? ne5t9date? or interval is &ULL? t3en t3e last values assi"ned to t3ose $arameters are used. 4unnin"? 4emovin"? and Brea.in" :o0s DB2$7QOB@R,N: 4uns a su0mitted 8o0 immediatel1? ,or e5am$le? $ass t3e 8o0 num0er t3at 1ou ant to run immediatel1 to t3e $rocedure EXEC,TE DB2$7QOB@R,N(0) DB2$7QOB@RE2O3E: 4emoves a su0mitted 8o0 ,rom t3e 8o0 @ueue? ,or e5am$le? Pass t3e 8o0 num0er t3at 1ou ant to remove ,rom t3e @ueue to t3e $rocedure. EXEC,TE DB2$7QOB@RE2O3E(0) DB2$7QOB@BROOEN: Mar.s a su0mitted 8o0 as 0ro.en? and a 0ro.en 8o0 ill not run? ,or e5am$le?

DBMS Unit 4

Procedural SQL Fundamentals: Part II

##

EXEC,TE DB2$7QOB@BROOEN(0. TR,E) ;ie in" In,ormation on Su0mitted :o0s Use t3e DBA7QOB$ dictionar1 vie to see t3e status o, su0mitted 8o0s.

$ELECT 6o&. lo'7%* r. n +t7dat . n +t7* (. &roB n. Mhat 8RO2 DBA7QOB$; Use t3e DBA7QOB$7R,NNING dictionar1 vie to dis$la1 8o0s t3at are currentl1 runnin". &sing t e DBMS_OUTPUT Package (3e DB2$7O,TP,T $ac.a"e out$uts values and messa"es ,rom an1 PL2SQL 0loc.. $unction or Procedure PU( NE:7LINE P,T7LINE GET7LINE GET7LINE$ ENABLEADI$ABLE UTL_FILE Package (3e Procedures and Functions it3in ,TL78ILE Pac.a"e: Description + ,unction t3at o$ens a ,ile ,or in$ut or out$ut and returns a ,ile 3andle used in su0se@uent I2O o$erations + ,unction t3at returns a Boolean value 3enever a ,ile 3andle re,ers to an o$en ,ile + $rocedure t3at reads a line o, te5t ,rom t3e o$ened ,ile and $laces t3e te5t in t3e out$ut 0u,,er $arameter Dt3e ma5imum siGe o, an in$ut record is 1?-/# 01tes unless 1ou s$eci,1 a lar"er siGe in t3e overloaded version o, 8OPENF + $rocedure t3at rites a te5t strin" stored in t3e 0u,,er $arameter to t3e o$ened ,ile Dno line terminator is a$$ended 01 $utA use ne 9line to terminate t3e line? or use P,T7LINE to rite a com$lete line it3 a terminatorF + ,ormatted $ut $rocedure it3 t o ,ormat s$eci,iers: C* and Xn Duse C* to su0stitute a value into t3e out$ut strin". Xn is a ne line c3aracterF $unction or Procedure FOP*& I$7OPEN <*(9LI&* Description +$$ends te5t ,rom t3e $rocedure to t3e current line o, t3e line out$ut 0u,,er Places an end9o,9line mar.er in t3e out$ut 0u,,er !om0ines t3e action o, P,T and NE:7LINE 4etrieves t3e current line ,rom t3e out$ut 0u,,er into t3e $rocedure 4etrieves an arra1 o, lines ,rom t3e out$ut 0u,,er into t3e $rocedure *na0les or disa0les calls to t3e DB2$7O,TP,T $rocedures

P,T. P,T7LINE

P,T8

DBMS Unit 4

Procedural SQL Fundamentals: Part II

#4

NE:7LINE 88L,$/ 8CLO$E 8CLO$E7ALL

Procedure t3at terminates a line in an out$ut ,ile Procedure t3at rites all data 0u,,ered in memor1 to a ,ile Procedure t3at closes an o$ened ,ile Procedure t3at closes all o$ened ,ile 3andles ,or t3e session

&ote: (3e ma5imum siGe o, an in$ut record is 1?-/# 01tes unless 1ou s$eci,1 a lar"er siGe in t3e overloaded version o, 8OPEN. *5ce$tions S$eci,ic to t3e ,TL78ILE Pac.a"e: (3e ,TL78ILE $ac.a"e declares se&en e5ce$tions t3at are raised to indicate an error condition in t3e o$eratin" s1stem ,ile $rocessin". Description (3e ,ile location or ,ilename as invalid. (3e OP*&9MOD* $arameter in FOP*& as invalid.

'(ception ame IN3ALID7PAT/ IN3ALID72ODE

IN3ALID78ILE/ANDLE (3e ,ile 3andle as invalid. IN3ALID7OPERATION (3e ,ile could not 0e o$ened or o$erated on as re@uested. READ7ERROR :RITE7ERROR INTERNAL7ERROR +n o$eratin" s1stem error occurred durin" t3e read o$eration. +n o$eratin" s1stem error occurred durin" t3e rite o$eration. +n uns$eci,ied error occurred in PL2SQL.

&ote: (3ese e5ce$tions must 0e $re,aced it3 t3e $ac.a"e name. ,TL78ILE $rocedures can also raise $rede,ined PL2SQL e5ce$tions suc3 as NO7DATA78O,ND or 3AL,E7ERROR. (3e 8OPEN and I$7OPEN Functions (3e S1nta5:

8,NCTION 8OPEN (lo(ation IN 3ARC/AR-. )il nam IN 3ARC/AR-. op n7mod IN 3ARC/AR-) RET,RN ,TL78ILE@8ILE7TDPE; 8,NCTION I$7OPEN ()il 7handl IN 8ILE7TDPE) RET,RN BOOLEAN; S1nta5 De,initions o, 8OPEN location Is t3e o$eratin">s1stem>s$eci,ic strin" t3at s$eci,ies t3e director1 or area in 3ic3 to o$en t3e ,ile filename Is t3e name o, t3e ,ile? includin" t3e e5tension? it3out an1 $at3in" in,ormation open_mode Is strin" t3at s$eci,ies 3o t3e ,ile is to 0e o$enedA Su$$orted values are:

DBMS Unit 4

Procedural SQL Fundamentals: Part II

#%

LrL read te5t Duse GET7LINEF L L rite te5t DP,T? P,T7LINE? NE:7LINE? P,T8? 88L,$/F LaL a$$end te5t DP,T? P,T7LINE? NE:7LINE? P,T8? 88L,$/F (3e ,unction I$7OPEN tests a ,ile 3andle to see i, it identi,ies an o$ened ,ile. It returns a Boolean value indicatin" 3et3er t3e ,ile 3as 0een o$ened 0ut not 1et closed. &ote: For t3e ,ull s1nta5? re,er to Oracle)i Su$$lied PL2SQL Pac.a"es and (1$es 4e,erence. *5am$le o, Usin" ,TL78ILE sal9status.s@l: creates a re$ort o, em$lo1ees ,or eac3 de$artment and t3eir salaries.

CREATE OR REPLACE PROCED,RE *al7*tat%* (p7)il dir IN 3ARC/AR-. p7)il nam IN 3ARC/AR-) I$ E7)il handl ,TL78ILE@8ILE7TDPE; C,R$OR mp7in)o I$ $ELECT la*t7nam . *alary. d partm nt7id 8RO2 mploy * ORDER BD d partm nt7id; E7n Md ptno mploy *@d partm nt7idCTDPE; E7oldd ptno mploy *@d partm nt7idCTDPE =; 1; BEGIN E7)il handl =; ,TL78ILE@8OPEN (p7)il dir. p7)il nam .4M4); ,TL78ILE@P,T8 (E7)il handl .4$ALARD REPORT= GENERATED ON C*Xn4. $D$DATE); ,TL78ILE@NE:7LINE (E7)il handl ); 8OR E7 mp7r ( IN mp7in)o LOOP E7n Md ptno =; E7 mp7r (@d partm nt7id; I8 E7n Md ptno <! E7oldd ptno T/EN ,TL78ILE@P,T8 (E7)il handl . 4DEPART2ENT= C*Xn4. E7 mp7r (@d partm nt7id); END I8; ,TL78ILE@P,T8 (E7)il handl .4 E2PLODEE= C* arn*= C*Xn4. E7 mp7r (@la*t7nam . E7 mp7r (@*alary); E7oldd ptno =; E7n Md ptno; END LOOP; ,TL78ILE@P,T7LINE (E7)il handl . 4FFF END O8 REPORT FFF4); ,TL78ILE@8CLO$E (E7)il handl );

DBMS Unit 4

Procedural SQL Fundamentals: Part II

#6

EXCEPTION :/EN ,TL78ILE@IN3ALID78ILE/ANDLE T/EN RAI$E7APPLICATION7ERROR ("-1110. 4InEalid 8il @4); :/EN ,TL78ILE@:RITE7ERROR T/EN RAI$E7APPLICATION7ERROR ("-111-. 4,na&l to Mrit to )il 4); END *al7*tat%*; (3is in,ormation is sent to a te5t ,ile 01 usin" t3e ,TL78ILE $rocedures and ,unctions. (3e varia0le v9,ile3andle uses a t1$e de,ined in t3e ,TL78ILE $ac.a"e. (3is $ac.a"e>de,ined t1$e is a record it3 a ,ield called ID o, t3e BINARD7INTEGER I$ RECORD (id BINARD7INTEGER); (3e contents o, ,ile9t1$e are $rivate to t3e ,TL78ILE $ac.a"e. Users o, t3e $ac.a"e s3ould not re,erence or c3an"e com$onents o, t3is record. (3e names o, t3e te5t ,ile and t3e location ,or t3e te5t ,ile are $rovided as $arameters to t3e $ro"ram. EXEC,TE *al7*tat%*(4C=X,TL78ILE4. 4$AL7RPT@TXT4) &ote: (3e ,ile location s3o n in t3e a0ove e5am$le is de,ined as value o, ,TL78ILE7DIR in t3e init&ora ,ile as ,ollo s: ,TL78ILE7DIR ; C=X,TL78ILE@ B3en readin" a com$lete ,ile in a loo$? 1ou need to e5it t3e loo$ usin" t3e NO7DATA78O,ND e5ce$tion. ,TL78ILE out$ut is sent s1nc3ronousl1. DB2$7O,TP,T $rocedures do not $roduce out$ut until t3e $rocedure is com$leted. Out$ut: (3e out$ut ,or t3is re$ort in t3e sal9r$t.t5t ,ile is as ,ollo s: $ALARD REPORT= GENERATED ON 1L"2AR"10 DEPART2ENT= 01 E2PLODEE= :hal n arn*= <<11 DEPART2ENT= -1 E2PLODEE= /art*t in arn*= 09111 E2PLODEE= 8ay arn*= H111 DEPART2ENT= 91 E2PLODEE= Rapha ly arn*= 00111 E2PLODEE= Ohoo arn*= 9011 @@@ DEPART2ENT= 011 E2PLODEE= Gr n& r' arn*= 0-111 datat1$e. TDPE )il 7typ

DBMS Unit 4

Procedural SQL Fundamentals: Part II

#7

@@@ DEPART2ENT= 001 E2PLODEE= /i''in* arn*= 0-111 E2PLODEE= Gi tT arn*= L911 E2PLODEE= Grant arn*= G111 FFF END O8 REPORT FFF * e UTL_HTTP Package (3e ,TL7/TTP $ac.a"e: *na0les =((P callouts ,rom PL2SQL and SQL to access data on t3e Internet !ontains t3e ,unctions RE5,E$T and RE5,E$T7PIECE$ 3ic3 ta.e t3e U4L o, a site as a $arameter? contact t3at site? and return t3e data o0tained ,rom t3at site 4e@uires a $ro51 $arameter to 0e s$eci,ied in t3e a0ove ,unctions? i, t3e client is 0e3ind a ,ire all 4aises INIT78AILED or RE5,E$T78AILED e5ce$tions i, =((P call ,ails 4e$orts an =(ML error messa"e i, s$eci,ied U4L is not accessi0le *5am$le: retrieve contents ,rom t3e U4L .oracle.com. $ELECT ,TL7/TTP@RE5,E$T(4http=AAMMM@ora(l @(om4. 4 d%" pro+y@%*@ora(l @(om4) 8RO2 D,AL; (3e second $arameter to t3e ,unction indicates t3e $ro51 0ecause t3e client 0ein" tested is 0e3ind a ,ire all. (3e retrieved out$ut is in =(ML ,ormat. *5am$le: retrieves u$ to 1-- $ieces o, data? eac3 o, ma5imum /--- 01tes ,rom t3e U4L. (3e num0er o, $ieces and t3e total len"t3 o, t3e data retrieved are $rinted.

DECLARE + ,TL7/TTP@/T2L7PIECE$; BEGIN + =; ,TL7/TTP@RE5,E$T7PIECE$(4http=AAMMM@ora(l @(omA4.011. 4 d%"pro+y@%*@ora(l @(om4); DB2$7O,TP,T@P,T7LINE(+@CO,NT ## 4 pi ( * M r r tri E d@4); DB2$7O,TP,T@P,T7LINE(4Mith total l n'th 4); I8 +@CO,NT < 0 T/EN DB2$7O,TP,T@P,T7LINE(414); EL$E DB2$7O,TP,T@P,T7LINE((-111F(+@CO,NT " 0)) KLENGT/(+(+@CO,NT))); END I8; END;

DBMS Unit 4

Procedural SQL Fundamentals: Part II

#'

&sing t e UTL_TCP Package (3e ,TL7TCP Pac.a"e: *na0les PL2SQL a$$lications to communicate it3 e5ternal (!P2IP>0ased servers usin" (!P2IP !ontains ,unctions to o$en and close connections? to read or rite 0inar1 or te5t data to or ,rom a service on an o$en connection 4e@uires remote 3ost and $ort as ell as local 3ost and $ort as ar"uments to its ,unctions 4aises e5ce$tions i, t3e 0u,,er siGe is too small? 3en no more data is availa0le to read ,rom a connection? 3en a "eneric net or. error occurs? or 3en 0ad ar"uments are $assed to a ,unction call (3e $ac.a"e contains ,unctions suc3 as: OPEN7CONNECTION: (3is ,unction o$ens a (!P2IP connection it3 t3e s$eci,ied remote and local 3ost and $ort details. (3e remote 3ost is t3e 3ost $rovidin" t3e service. (3e remote $ort is t3e $ort num0er on 3ic3 t3e service is listenin" ,or connections. (3e local 3ost and $ort num0ers re$resent t3ose o, t3e 3ost $rovidin" t3e service. (3e ,unction returns a connection o, PL2SQL record t1$e. CLO$E7CONNECTION: (3is $rocedure closes an o$en (!P2IP connection. It ta.es t3e connection details o, a $reviousl1 o$ened connection as $arameter. (3e $rocedure !LOS*9+LL9!O&&*!(IO&S closes all o$en connections. READ7BINARD()ATEXT()ALINE(): (3is ,unction receives 0inar1? te5t? or te5t line data ,rom a service on an o$en connection. :RITE7BINARD()ATEXT()ALINE(): (3is ,unction transmits 0inar1? te5t? or te5t line messa"e to a service on an o$en connection. Ot er Oracle+supplied packages Packa%e Description DBMS9+L*4( Provides noti,ication o, data0ase events DB2$7APPLICATION +llo s a$$lication tools and a$$lication develo$ers to in,orm t3e 7IN8O data0ase o, t3e 3i"3 level o, actions t3e1 are currentl1 $er,ormin" DB2$7DE$CRIBE DB2$7LOCO DB2$7$E$$ION 4eturns a descri$tion o, t3e ar"uments ,or a stored $rocedure 4e@uests? converts? and releases userloc.s? 3ic3 are mana"ed 01 t3e 4DBMS loc. mana"ement services Provides access to SQL session in,ormation

DB2$7$/ARED7POOL Nee$s o08ects in s3ared memor1 DB2$7TRAN$ACTION !ontrols lo"ical transactions and im$roves t3e $er,ormance o, s3ort?

DBMS Unit 4

Procedural SQL Fundamentals: Part II

#)

nondistri0uted transactions DB2$7,TILITD !+L*&D+4 DB2$7ALERT +nal1Ges o08ects in a $articular sc3ema? c3ec.s 3et3er t3e server is runnin" in $arallel mode? and returns t3e time Provides calendar maintenance ,unctions Su$$orts as1nc3ronous noti,ication o, data0ase events. Messa"es or alerts are sent on a !OMMI( command. Messa"e transmittal is one a1? 0ut one sender can alert several receivers.

DB2$7APPLICATION Is used to re"ister an a$$lication name it3 t3e data0ase ,or auditin" 7IN8O or $er,ormance trac.in" $ur$oses DB2$7A5 Provides messa"e @ueuin" as $art o, t3e Oracle serverA is used to add a messa"e Do, a $rede,ined o08ect t1$eF onto a @ueue or de@ueue a messa"e Is used to $er,orm administrative ,unctions on a @ueue or @ueue ta0le ,or messa"es o, a $rede,ined o08ect t1$e Is used to em0ed t3e e@uivalent o, t3e SQL commands +L(*4? !OMPIL*? and +&+LCO* it3in 1our PL2SQL $ro"rams DBMS9D*BU< + PL2SQL +PI to t3e PL2SQL de0u""er la1er? Pro0e? in t3e Oracle server

DB2$7A5AD2 DB2$7DDL

DB$27DE8ER Is used to 0uild and administer de,erred remote $rocedure calls Duse DB2$7DE8ER75,ERD o, t3is ,eature re@uires t3e 4e$lication O$tionF DB2$7DE8ER7$D$ DB2$7DE$CRIBE DB2$7 DI$TRIBR,TED7 TR,$T7AD2IN DB2$7/$ Is used to descri0e t3e ar"uments o, a stored $rocedure Is used to maintain t3e (rusted Servers list? 3ic3 is used in con8unction it3 t3e list at t3e central aut3orit1 to determine 3et3er a $rivile"ed data0ase lin. ,rom a $articular server can 0e acce$ted Is used to administer 3etero"eneous services 01 re"isterin" or dro$$in" distri0uted e5ternal $rocedures? remote li0raries? and non> Oracle s1stems D1ou use d0ms93s to create or dro$ some initialiGation varia0les ,or non>Oracle s1stemsF

DB2$7/$7EXTPROC *na0les 3etero"eneous services to esta0lis3 securit1 ,or distri0uted e5ternal $rocedures DB2$7/$7 *na0les 3etero"eneous services to send $ass>t3rou"3 SQL statements PA$$T/RO,G/ to non>Oracle s1stems DB2$7IOT DB2$7QOB Is used to sc3edule administrative $rocedures t3at 1ou ant $er,ormed at $eriodic intervalsA is also t3e inter,ace ,or t3e 8o0 @ueue Is used to sc3edule administrative $rocedures t3at 1ou ant $er,ormed at $eriodic intervals

DBMS Unit 4

Procedural SQL Fundamentals: Part II

4-

DB2$7LOB

Provides "eneral $ur$ose routines ,or o$erations on Oracle lar"e o08ects DLOBsF data t1$es: BLOB? !LOB Dread onl1F and BFIL*S Dread>onl1F Is used to re@uest? convert? and release loc.s t3rou"3 Oracle Loc. Mana"ement services Provides ,unctions to initialiGe and run t3e lo" reader Queries t3e dictionar1 ta0les o, t3e current data0ase? and creates a te5t 0ased ,ile containin" t3eir contents

DB2$7LOCO DB2$7LOG2NR DB2$7LOG2NR7D

DB2$7O88LINE7OG Provides $u0lic +PIs ,or o,,line instantiation o, master "rou$s DB2$7O88LINE7 Provides $u0lic +PIs ,or o,,line instantiation o, sna$s3ots $NAP$/OT DB2$7OLAP DB2$7ORACLE7 TRACE7AGENT DB2$7ORACLE7 TRACE7,$ER DB2$7O,TP,T DB2$7PCLX,TIL DB2$7PIPE DB2$7PRO8ILER DB2$7RANDO2 Provides $rocedures ,or summaries? dimensions? and @uer1 re rites Provides client calla0le inter,aces to t3e Oracle (4+!* instrumentation it3in t3e Oracle7 server Provides $u0lic access to t3e Oracle7 release server Oracle (4+!* instrumentation ,or t3e callin" user +ccumulates in,ormation in a 0u,,er so t3at it can 0e retrieved out later Provides intra$artition $arallelism ,or creatin" $artition ise local inde5es Provides a DBMS $i$e service t3at ena0les messa"es to 0e sent 0et een sessions Provides a Pro0e Pro,iler +PI to $ro,ile e5istin" PL2SQL a$$lications and identi,1 $er,ormance 0ottlenec.s Provides a 0uilt>in random num0er "enerator

DB2$7RECTI8IER7 Provides +PIs used to detect and resolve data inconsistencies DI88 0et een t o re$licated sites DB2$7RE8RE$/ Is used to create "rou$s o, sna$s3ots t3at can 0e re,res3ed to"et3er to a transactionall1 consistent $oint in timeA re@uires t3e Distri0uted o$tion DB2$7REPAIR DB2$7REPCAT DB2$7REPCAT7 AD2IN DB2$7REPCAT7 IN$TATIATE Provides data corru$tion re$air $rocedures Provides routines to administer and u$date t3e re$lication catalo" and environmentA re@uires t3e 4e$lication o$tion Is used to create users it3 t3e $rivile"es needed 01 t3e s1mmetric re$lication ,acilit1A re@uires t3e 4e$lication o$tion Instantiates de$lo1ment tem$latesA re@uires t3e 4e$lication o$tion

DBMS Unit 4

Procedural SQL Fundamentals: Part II

41

DB2$7REPCAT7RGT !ontrols t3e maintenance and de,inition o, re,res3 "rou$ tem$latesA re@uires t3e 4e$lication o$tion DB2$7REP,TIL Provides routines to "enerate s3ado ta0les? tri""ers? and $ac.a"es ,or ta0le re$lication DB2$7RE$O,RCE7 2ANAGER DB2$7RE$O,RCE7 2ANAGER7PRI3$ DB2$7RL$ DB2$7RO:ID DB2$7$E$$ION Maintains $lans? consumer "rou$s? and $lan directivesA it also $rovides semantics so t3at 1ou ma1 "rou$ to"et3er c3an"es to t3e $lan sc3ema Maintains $rivile"es associated it3 resource consumer "rou$s Provides ro >level securit1 administrative inter,ace Is used to "et in,ormation a0out 4OBIDs? includin" t3e data 0loc. num0er? t3e o08ect num0er? and ot3er com$onents *na0les $ro"rammatic use o, t3e SQL +L(*4 S*SSIO& statement as ell as ot3er session>level commands out it3 t3e normal L4U mec3anism DB2$7$NAP$/OT Is used to re,res3 one or more sna$s3ots t3at are not $art o, t3e same re,res3 "rou$ and $ur"e lo"sA use o, t3is ,eature re@uires t3e Distri0uted o$tion Provides se"ment s$ace in,ormation not availa0le t3rou"3 standard vie s t3rou"3 standard SQL D$2$7$5L DB2$7$TANDARD DB2$7$TAT$ DB2$7TRACE Is used to rite stored $rocedure and anon1mous PL2SQL 0loc.s usin" d1namic SQLA also used to $arse an1 DML or DDL statement Provides lan"ua"e ,acilities t3at 3el$ 1our a$$lication interact it3 t3e Oracle server Provides a mec3anism ,or users to vie and modi,1 o$timiGer statistics "at3ered ,or data0ase o08ects Provides routines to start and sto$ PL2SQL tracin" mana"ement DB2$7TT$ DB2$7,TILITD DEB,G7EXTPROC !3ec.s 3et3er i, t3e trans$orta0le set is sel,>contained Provides ,unctionalit1 ,or mana"in" $rocedures? re$ortin" errors? and ot3er in,ormation Is used to de0u" e5ternal $rocedures on $lat,orms it3 de0u""ers t3at can attac3 to a runnin" $rocess

DB2$7$/ARED7POOL Is used to .ee$ o08ects in s3ared memor1? so t3at t3e1 are not a"ed

DB2$7$PACE

DB2$7$PACE7AD2IN Provides ta0les$ace and se"ment s$ace administration not availa0le

DB2$7TRAN$ACTION Provides $rocedures ,or a $ro"rammatic inter,ace to transaction

DBMS Unit 4

Procedural SQL Fundamentals: Part II

4/

O,TLN7POG PLITBL2 $DO7AD2IN $DO7GEO2 $DO72IGRATE $DO7T,NE $TANDARD TI2E$ERIE$ TI2E$CALE T$TOOL$ ,TL7COLL ,TL78ILE

Provides t3e inter,ace ,or $rocedures and ,unctions associated it3 mana"ement o, stored outlines =andles inde5>ta0le o$erations Provides ,unctions im$lementin" s$atial inde5 creation and maintenance ,or s$atial o08ects Provides ,unctions im$lementin" "eometric o$erations on s$atial o08ects Provides ,unctions ,or mi"ratin" s$atial data ,rom release 7.#.# and 7.#.4 to '.1.5 Provides ,unctions ,or selectin" $arameters t3at determine t3e 0e3avior o, t3e s$atial inde5in" sc3eme used in t3e S$atial !artrid"e Declares t1$es? e5ce$tions? and su0$ro"rams t3at are availa0le automaticall1 to ever1 PL2SQL $ro"ram Provides ,unctions t3at $er,orm o$erations? suc3 as e5traction? retrieval? arit3metic? and a""re"ation? on time series data Provides scale>u$ and scale>do n ,unctions Provides administrative tools $rocedures *na0les PL2SQL $ro"rams to use collection locators to @uer1 and u$date *na0les 1our PL2SQL $ro"rams to read and rite o$eratin" s1stem DOSF te5t ,iles and $rovides a restricted version o, standard OS stream ,ile I2O *na0les =((P callouts ,rom PL2SQL and SQL to access data on t3e Internet or to call Oracle Be0 Server !artrid"es Provides ,unctions ,or convertin" !OBOL numeric data into Oracle num0ers and Oracle num0ers into !OBOL numeric data Provides SQL ,unctions ,or 4+B data t1$es t3at concatenate? o0tain su0strin"? and so on? to and ,rom 4+B data t1$es *na0les a PL2SQL $ro"ram to access an o08ect 01 $rovidin" a re,erence to t3e o08ect Provides anal1tical and conversion ,unctions ,or visual in,ormation retrieval

,TL7/TTP ,TL7PG ,TL7RA: ,TL7RE8 3IR7POG

Trigger (1$e o, a (ri""er: Is a PL2SQL 0loc. or a PL2SQL $rocedure associated it3 a ta0le? vie ? sc3ema? or t3e data0ase

DBMS Unit 4

Procedural SQL Fundamentals: Part II

4#

*5ecutes im$licitl1 3enever a $articular event ta.es $lace !an 0e eit3er: +$$lication tri""er: Fires 3enever an event occurs it3 a $articular a$$lication Data0ase tri""er: Fires 3enever a data event Dsuc3 as DMLF or s1stem event Dsuc3 as lo"on or s3utdo nF occurs on a sc3ema or data0ase Data0ase tri""ers e5ecute im$licitl1 3en a data event suc3 as DML on a ta0le Dan IN$ERT? ,PDATE? or DELETE tri""erin" statementF? an IN$TEAD O8 tri""er on a vie ? or data de,inition lan"ua"e DDDLF statements suc3 as CREATE and ALTER are issued? no matter 3ic3 user is connected or 3ic3 a$$lication is used. *5am$le o, Data0ase (ri""er

Creating D'( )riggers (3e com$onents o, t3e tri""er: Part (ri""er timin" Description B3en t3e tri""er ,ires in relation to t3e tri""erin" event Possible !alues BE8ORE A8TER IN$TEAD O8

(ri""erin" event B3ic3 data mani$ulation o$eration on t3e IN$ERT ,PDATE ta0le or vie causes t3e tri""er to ,ire DELETE (ri""er t1$e =o man1 times t3e tri""er 0od1 e5ecutes Statement 4o

(ri""er 0od1 B3at action t3e tri""er $er,orms !om$lete PL2SQL 0loc. BE8ORE (ri""ers (3is t1$e o, tri""er is ,re@uentl1 used in t3e ,ollo in"

DBMS Unit 4

Procedural SQL Fundamentals: Part II

44

situations: (o determine 3et3er t3at tri""erin" statement s3ould 0e allo ed to com$lete. D(3is situation ena0les 1ou to eliminate unnecessar1 $rocessin" o, t3e tri""erin" statement and its eventual roll0ac. in cases 3ere an e5ce$tion is raised in t3e tri""erin" action.F (o derive column values 0e,ore com$letin" a tri""erin" I&S*4( or UPD+(* statement. (o initialiGe "lo0al varia0les or ,la"s? and to validate com$le5 0usiness rules. A8TER (ri""ers (3is t1$e o, tri""er is ,re@uentl1 used in t3e ,ollo in" situations: (o com$lete t3e tri""erin" statement 0e,ore e5ecutin" t3e tri""erin" action. (o $er,orm di,,erent actions on t3e same tri""erin" statement i, a B*FO4* tri""er is alread1 $resent. IN$TEAD O8 (ri""ers (3is t1$e o, tri""er is used to $rovide a trans$arent a1 o, modi,1in" vie s t3at cannot 0e modi,ied directl1 t3rou"3 SQL DML statements 0ecause t3e vie is not in3erentl1 modi,ia0le. (3e tri""erin" event or statement can 0e an IN$ERT? ,PDATE? or DELETE statement on a ta0le. B3en t3e tri""erin" event is an ,PDATE statement? 1ou can include a column list to identi,1 3ic3 columns must 0e c3an"ed to ,ire t3e tri""er. Cou cannot s$eci,1 a column list ,or an IN$ERT or ,or a DELETE statement? 0ecause t3e1 al a1s a,,ect entire ro s. (3e tri""erin" event can contain one? t o? or all t3ree o, t3ese DML o$erations. Statement (ri""er + statement tri""er is ,ired once on 0e3al, o, t3e tri""erin" event? even i, no ro s are a,,ected at all. Statement tri""ers are use,ul i, t3e tri""er action does not de$end on t3e data ,rom ro s t3at are a,,ected or on data $rovided 01 t3e tri""erin" event itsel,: ,or e5am$le? a tri""er t3at $er,orms a com$le5 securit1 c3ec. on t3e current user. 4o (ri""er + ro tri""er ,ires eac3 time t3e ta0le is a,,ected 01 t3e tri""erin" event. I, t3e tri""erin" event a,,ects no ro s? a ro tri""er is not e5ecuted. 4o tri""ers are use,ul i, t3e tri""er action de$ends on data o, ro s t3at are a,,ected or on data $rovided 01 t3e tri""erin" event itsel,. (3e tri""er action de,ines 3at needs to 0e done 3en t3e tri""erin" event is issued. (3e siGe o, a tri""er cannot 0e more t3an #/ N. Firin" Se@uence For e5am$le? use t3e ,ollo in" ,irin" se@uence ,or a tri""er on a ta0le? 3en a sin"le ro is mani$ulated:

DBMS Unit 4

Procedural SQL Fundamentals: Part II

4%

DML Statement: IN$ERT INTO d partm nt* (d partm nt7id. d partm nt7nam . lo(ation7id) 3AL,E$ (<11. 4CON$,LTING4. -<11); (ri""er +ction:

Basic *rigger Synta$, + tri""er is ,ollo in" t3e ,ormat 0elo CREATE >OR REPLACE? TRIGGER trigger_name timing e ent! >OR e ent" OR e ent#? ON table_name trigger_body In t3e s1nta5 trigger name Is t3e name o, t3e tri""er timing Indicates t3e time 3en t3e tri""er ,ires in relation to t3e tri""erin" event: BE8ORE A8TER Identi,ies t3e data mani$ulation o$eration t3at causes t3e tri""er to ,ire: IN$ERT ,PDATE >O8 (ol%mn? DELETE

e ent

table/ ie$_nam Indicates t3e ta0le associated it3 t3e tri""er e trigger body Is t3e tri""er 0od1 t3at de,ines t3e action $er,ormed 01 t3e tri""er? 0e"innin" it3 eit3er DECLARE or BEGIN? endin" it3 END? or a call to a $rocedure

*5am$le: create a tri""er to restrict inserts into t3e *MP ta0le to certain 0usiness 3ours?

DBMS Unit 4

Procedural SQL Fundamentals: Part II

46

Monda1 t3rou"3 Frida1. CREATE OR REPLACE TRIGGER * (%r 7 mp BE8ORE IN$ERT ON mp BEGIN I8 (TO7C/AR($D$DATE.4DD4) IN (4$AT4.4$,N4)) OR (TO7C/AR($D$DATE.4//-<=2I4) NOT BET:EEN 41L=114 AND 40L=114) T/EN RAI$E7APPLICATION7ERROR ("-1J11.4Do% may in* rt into E2P ta&l only d%rin' &%*in ** ho%r*@4); END I8; END; I, a user attem$ts to insert a ro into t3e E2PLODEE$ ta0le on Saturda1? t3e user sees t3e messa"e? t3e tri""er ,ails? and t3e tri""erin" statement is rolled 0ac.. 4emem0er t3at t3e RAI$E7APPLICATION7ERROR is a server>side 0uilt>in $rocedure t3at returns an error to t3e user and causes t3e PL2SQL 0loc. to ,ail. B3en a data0ase tri""er ,ails? t3e tri""erin" statement is automaticall1 rolled 0ac. 01 t3e Oracle server. (estin" S*!U4*9*MP IN$ERT INTO mp ( mpno. nam . hir dat . 6o&. *al. d ptno) 3AL,E$ (911. 4$mith4. $D$DATE. 4IT7PROG4. <J11. H1); B3en t3e date and time are out o, t3e 0usiness timin"s s$eci,ied in t3e tri""er? 1ou "et t3e error messa"e *5am$le: Usin" !onditional Predicates

CREATE OR REPLACE TRIGGER * (%r 7 mp BE8ORE IN$ERT OR ,PDATE OR DELETE ON mploy * BEGIN I8 (TO7C/AR ($D$DATE.4DD4) IN (4$AT4.4$,N4)) OR (TO7C/AR ($D$DATE. 4//-<4) NOT BET:EEN 41L4 AND 40L4) T/EN I8 DELETING T/EN RAI$E7APPLICATION7ERROR ("-1J1-.4Do% may d l t )rom E2P ta&l only d%rin' &%*in ** ho%r*@4); EL$I8 IN$ERTING T/EN RAI$E7APPLICATION7ERROR ("-1J11.4Do% may in* rt into E2P ta&l only d%rin' &%*in ** ho%r*@4); EL$I8 ,PDATING (4$ALARD4) T/EN

DBMS Unit 4

Procedural SQL Fundamentals: Part II

47

RAI$E7APPLICATION7ERROR ("-1J19.4Do% may %pdat $ALARD only d%rin' &%*in ** ho%r*@4); EL$E RAI$E7APPLICATION7ERROR ("-1J1<.4Do% may %pdat E2P ta&l only d%rin' normal ho%r*@4); END I8; END I8; END; Cou can com0ine several tri""erin" events into one 01 ta.in" advanta"e o, t3e s$ecial conditional $redicates I&S*4(I&<? UPD+(I&<? and D*L*(I&< it3in t3e tri""er 0od1. %reating a D'L !o- *rigger S1nta5: CREATE >OR REPLACE? TRIGGER tri'' r7nam timin' E nt0 >OR E nt- OR E nt9? ON ta&l 7nam >RE8ERENCING OLD A$ old # NE: A$ n M? 8OR EAC/ RO: >:/EN ((ondition)? tri'' r7&ody S1nta5 ,or !reatin" a 4o (ri""er tri'' r7nam Is t3e name o, t3e tri""er timin' Indicates t3e time 3en t3e tri""er ,ires in relation to t3e tri""erin" event: BE8ORE A8TER IN$TEAD O8 Identi,ies t3e data mani$ulation o$eration t3at causes t3e tri""er to ,ire: IN$ERT ,PDATE >O8 column? DELETE Indicates t3e ta0le associated it3 t3e tri""er S$eci,ies correlation names ,or t3e old and ne values o, t3e current ro D(3e de,ault values are OLD and NE:F

E nt

ta&l 7nam RE8ERENCING

8OR EAC/ RO: Desi"nates t3at t3e tri""er is a ro tri""er :/EN S$eci,ies t3e tri""er restrictionA D(3is conditional $redicate must 0e

DBMS Unit 4

Procedural SQL Fundamentals: Part II

4'

enclosed in $arent3esis and is evaluated ,or eac3 ro to determine 3et3er or not t3e tri""er 0od1 is e5ecuted.F tri'' r &ody Is t3e tri""er 0od1 t3at de,ines t3e action $er,ormed 01 t3e tri""er? 0e"innin" it3 eit3er DECLARE or BEGIN? endin" it3 END? or a call to a $rocedure Some im$ortant $oints to note: Cou can create onl1 BE8ORE and A8TER tri""ers ,or ta0les. DIN$TEAD O8 tri""ers are onl1 availa0le ,or vie sA t1$icall1 t3e1 are used to im$lement vie u$dates.F Cou ma1 s$eci,1 u$ to t3ree tri""erin" events usin" t3e .e1 ord OR. Furt3ermore? ,PDATE can 0e o$tionall1 ,ollo ed 01 t3e .e1 ord O8 and a list o, attri0uteDsF in Pta0le9nameJ. I, $resent? t3e O8 clause de,ines t3e event to 0e onl1 an u$date o, t3e attri0uteDsF listed a,ter O8. =ere are some e5am$les: @@@ IN$ERT ON R @@@ @@@ IN$ERT OR DELETE OR ,PDATE ON R @@@ @@@ ,PDATE O8 A. B OR IN$ERT ON R @@@ I, 8OR EAC/ RO: o$tion is s$eci,ied? t3e tri""er is ro >levelA ot3er ise? t3e tri""er is statement>level. Onl1 ,or ro >level tri""ers: (3e s$ecial varia0les NE: and OLD are availa0le to re,er to ne and old tu$les res$ectivel1. &ote: In t3e tri""er 0od1? NE: and OLD must 0e $receded 01 a colon DK:KF? 0ut in t3e :/EN clause? t3e1 do not 3ave a $recedin" colonQ See e5am$le 0elo . (3e RE8ERENCING clause can 0e used to assi"n aliases to t3e varia0les NE: and OLD. + tri""er restriction can 0e s$eci,ied in t3e :/EN clause? enclosed 01

$arent3eses. (3e tri""er restriction is a SQL condition t3at must 0e satis,ied in order ,or Oracle to ,ire t3e tri""er. (3is condition cannot contain su0@ueries. Bit3out t3e :/EN clause? t3e tri""er is ,ired ,or eac3 ro . <tri'' r7&ody! is a PL2SQL 0loc.? rat3er t3an se@uence o, SQL statements. Oracle 3as $laced certain restrictions on 3at 1ou can do in Ptri""er90od1J? in order to avoid situations 3ere one tri""er $er,orms an action t3at tri""ers a second tri""er? 3ic3 t3en tri""ers a t3ird? and so on? 3ic3 could $otentiall1 create an in,inite loo$. (3e restrictions on Ptri""er90od1J include:

DBMS Unit 4

Procedural SQL Fundamentals: Part II

4)

Cou cannot modi,1 t3e same relation 3ose modi,ication is t3e event tri""erin" t3e tri""er. Cou cannot modi,1 a relation connected to t3e tri""erin" relation 01 anot3er constraint suc3 as a ,orei"n>.e1 constraint. *5am$le: Be illustrate OracleEs s1nta5 ,or creatin" a tri""er t3rou"3 an e5am$le 0ased on t3e ,ollo in" t o ta0les: CREATE TABLE T< (a INTEGER. & C/AR(01)); CREATE TABLE TJ (( C/AR(01). d INTEGER); Be create a tri""er t3at ma1 insert a tu$le into (% 3en a tu$le is inserted into (4. S$eci,icall1? t3e tri""er c3ec.s 3et3er t3e ne tu$le 3as a ,irst com$onent 1- or less? and i, so inserts t3e reverse tu$le into (%:

CREATE TRIGGER tri'0 A8TER IN$ERT ON T< RE8ERENCING NE: A$ n MRoM 8OR EAC/ RO: :/EN (n MRoM@a <; 01) BEGIN IN$ERT INTO TJ 3AL,E$(=n MRoM@&. =n MRoM@a); END tri'0; @ r%n; &otice t3at e end t3e CREATE TRIGGER statement it3 a dot and run? as ,or all PL2SQL statements in "eneral. 4unnin" t3e CREATE TRIGGER statement onl1 creates t3e tri""erA it does not e5ecute t3e tri""er. Onl1 a tri""erin" event? suc3 as an insertion into (4 in t3is e5am$le? causes t3e tri""er to e5ecute. Usin" OLD and NE: Quali,iers

CREATE OR REPLACE TRIGGER a%dit7 mp7Eal% * A8TER DELETE OR IN$ERT OR ,PDATE ON mp 8OR EAC/ RO: BEGIN IN$ERT INTO a%dit7 mp7ta&l (%* r7nam . tim *tamp. id. old7 nam . n M7 nam . old76o&. n M76o&. old7*al. n M7*al) 3AL,E$ (,$ER. $D$DATE. =OLD@ mpno. =OLD@ nam . =NE:@ nam . =OLD@6o&. =NE:@6o&. =OLD@*al. =NE:@*al); END; Bit3in a RO: tri""er? re,erence t3e value o, a column 0e,ore and a,ter t3e data

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%-

c3an"e 01 $re,i5in" it it3 t3e OLD and NE: @uali,ier. Data )peration IN$ERT ,PDATE DELETE )ld !alue &ULL ;alue 0e,ore u$date e" !alue Inserted value ;alue a,ter u$date

;alue 0e,ore delete &ULL (3e OLD and NE: @uali,iers are availa0le onl1 in RO: tri""ers.

Pre,i5 t3ese @uali,iers it3 a colon D:F in ever1 SQL and PL2SQL statement. (3ere is no colon D:F $re,i5 i, t3e @uali,iers are re,erenced in t3e :/EN restrictin" condition. &ote: 4o tri""ers can decrease t3e $er,ormance i, 1ou do a lot o, u$dates on lar"er ta0les. *5am$le: Usin" A%dit7Emp7Ta&l

IN$ERT INTO mp ( mpno. nam . 6o&. *al. @@@) 3AL,E$ (NNN. 4T mp mp4. 4$A7REP4. 0111. @@@); ,PDATE mp $ET *al ; -111. nam :/ERE mpno ; NNN;

; 4$mith4

!reate a tri""er on t3e *MP ta0le to add ro s to a user ta0le? A,DIT7E2P7TABLE? lo""in" a userLs activit1 a"ainst t3e E2P ta0le. (3e tri""er records t3e values o, several columns 0ot3 0e,ore and a,ter t3e data c3an"es 01 usin" t3e OLD and NE: @uali,iers it3 t3e res$ective column name. *5am$le o, 4estrictin" a 4o (ri""er: !reate a tri""er on t3e E2P ta0le to calculate an em$lo1eeLs commission 3en a ro is added to t3e E2P ta0le? or 3en an em$lo1eeLs salar1 is modi,ied.

CREATE OR REPLACE TRIGGER d riE 7(omm BE8ORE IN$ERT OR ,PDATE O8 *alary ON mp 8OR EAC/ RO: :/EN (NE:@6o& ; 4$A7REP4) BEGIN I8 IN$ERTING T/EN =NE:@(omm =; 1; EL$I8 =OLD@(omm I$ N,LL T/EN =NE:@(omm =; 1; EL$E =NE:@(omm =; =OLD@(omm K 1@1J;

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%1

END I8; END; (o restrict t3e tri""er action to t3ose ro s t3at satis,1 a certain condition? $rovide a :/EN clause. INSTEAD OF )riggers Use IN$TEAD O8 tri""ers to modi,1 data in 3ic3 t3e DML statement 3as 0een issued

a"ainst an in3erentl1 nonu$data0le vie . (3ese tri""ers are called IN$TEAD O8 tri""ers 0ecause? unli.e ot3er tri""ers? t3e Oracle server ,ires t3e tri""er instead o, e5ecutin" t3e tri""erin" statement. (3is tri""er is used to $er,orm an IN$ERT? ,PDATE? or DELETE o$eration directl1 on t3e underl1in" ta0les. &ote: I, a vie is in3erentl1 u$datea0le and 3as IN$TEAD O8 tri""ers? t3e tri""ers ta.e $recedence. IN$TEAD O8 tri""ers are ro tri""ers.

%reating an INSTEAD OF *rigger S1nta5: CREATE >OR REPLACE? TRIGGER tri'' r7nam IN$TEAD O8 E nt0 >OR E nt- OR E nt9?

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%/

ON Ei M7nam >RE8ERENCING OLD A$ old # NE: A$ n M? >8OR EAC/ RO:? tri'' r7&ody S1nta5 ,or !reatin" an IN$TEAD O8 (ri""er tri%%er_name IN$TEAD O8 E nt Is the name of the tri%%er* Indicates t3at t3e tri""er 0elon"s to a vie Identi,ies t3e data mani$ulation o$eration t3at causes t3e tri""er to ,ire: IN$ERT ,PDATE >O8 column? DELETE Indicates t3e vie associated it3 tri""er S$eci,ies correlation names ,or t3e old and ne values o, t3e current ro D(3e de,aults are OLD and NE:F Desi"nates t3e tri""er to 0e a ro tri""erA IN$TEAD O8 tri""ers can onl1 0e ro tri""ers: i, t3is is omitted? t3e tri""er is still de,ined as a ro tri""er. tri'' r &ody Is t3e tri""er 0od1 t3at de,ines t3e action $er,ormed 01 t3e tri""er? 0e"innin" it3 eit3er DECLARE or BEGIN? and endin" it3 END or a call to a $rocedure &ote: IN$TEAD O8 tri""ers can 0e ritten onl1 ,or vie s. BE8ORE and A8TER o$tions are not valid. *5am$le: (3e ,ollo in" e5am$le creates t o ne ta0les? NE:7E2P$ and NE:7DEPT$? 0ased on t3e E2P and DEPT ta0les res$ectivel1. It also creates an E2P7DETAIL$ vie ,rom t3e E2P and DEPT ta0les. (3e e5am$le also creates an IN$TEAD O8 tri""er? NE:7E2P7DEPT. B3en a ro is inserted into t3e E2P7DETAIL$ vie ? instead o, insertin" t3e ro directl1 into t3e vie ? ro s are added into t3e NE:7E2P$ and NE:7DEPT$ ta0les? 0ased on t3e data in t3e IN$ERT statement. Similarl1? 3en a ro is modi,ied or deleted t3rou"3 t3e E2P7DETAIL$ vie ? corres$ondin" ro s in t3e NE:7E2P$ and NE:7DEPT$ ta0les are a,,ected. CREATE TABLE n M7 mp* A$ $ELECT mpno. nam . *al. d ptno. 6o&. hir dat 8RO2 mp;

Ei M7nam RE8ERENCING 8OR EAC/ RO:

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%#

CREATE TABLE n M7d pt* A$ $ELECT d@d ptno. d@dnam . d@lo(. *%m( @*al) tot7d pt7*al 8RO2 mp . d pt d :/ERE @d ptno ; d@d ptno GRO,P BD d@d ptno. d@dnam . d@lo(; CREATE 3IE: mp7d tail* A$ $ELECT @ mpno. @ nam . @*al. d@lo( 8RO2 mp . d pt d :/ERE @d ptno ; d@d ptno;

@d ptno.

@6o&. d@dnam .

CREATE OR REPLACE TRIGGER n M7 mp7d pt IN$TEAD O8 IN$ERT OR ,PDATE OR DELETE ON mp7d tail* 8OR EAC/ RO: BEGIN I8 IN$ERTING T/EN IN$ERT INTO n M7 mp* 3AL,E$ (=NE:@ mpno. =NE:@ nam . =NE:@*al. =NE:@d ptno. =N M@6o&. $D$DATE); ,PDATE n M7d pt* $ET tot7d pt7*al ; tot7d pt7*al K =NE:@*al :/ERE d ptno ; =NE:@d ptno; EL$I8 DELETING T/EN DELETE 8RO2 n M7 mp* :/ERE mpno ; =OLD@ mpno; ,PDATE n M7d pt* $ET tot7d pt7*al ; tot7d pt7*al " =OLD@*al :/ERE d ptno ; =OLD@d ptno; EL$I8 ,PDATING (4*alary4) T/EN ,PDATE n M7 mp* $ET *al ; =NE:@*al :/ERE mpno ; =OLD@ mpno; ,PDATE n M7d pt* $ET tot7d pt7*al ; tot7d pt7*al K (=NE:@*al " =OLD@*al) :/ERE d ptno ; =OLD@d ptno; EL$I8 ,PDATING (4d ptno4) T/EN

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%4

,PDATE n M7 mp* $ET d ptno ; =NE:@d ptno :/ERE mpno ; =OLD@ mpno; ,PDATE n M7d pt* $ET tot7d pt7*al ; tot7d pt7*al " =OLD@*al :/ERE d ptno ; =OLD@d ptno; ,PDATE n M7d pt* $ET tot7d pt7*al ; tot7d pt7*al K =NE:@*al :/ERE d ptno ; =NE:@d ptno; END I8; END; +ssume t3at an em$lo1ee name ill 0e inserted usin" t3e vie E2P7DETAIL$ t3at is created 0ased on t3e E2P and DEPT ta0les. !reate a tri""er t3at results in t3e a$$ro$riate IN$ERT and ,PDATE to t3e 0ase ta0les. =o does t3is tri""er e5am$le or.R IN$ERT into E2P7DETAIL$ t3at is 0ased on E2P and DEPT ta0les? ,or e5am$le?

IN$ERT INTO mp7d tail*( mpno. nam . *al. d ptno. 6o&) 3AL,E$(N110.4ABBOTT4.9111.01.4/R72AN4); Because o, t3e IN$TEAD O8 TRIGGER on t3e vie E2P7DETAIL$? instead o, insertin" t3e ne em$lo1ee record into t3e E2P ta0le: + ro is inserted into t3e NE:7E2P$ ta0le? 0ut not3in" c3an"ed on t3e vie E2P7DETAIL$. (3e TOTAL7DEPT7$AL column o, t3e NE:7DEPT$ ta0le is u$dated. (3e salar1 value su$$lied ,or t3e ne em$lo1ee is added to t3e e5istin" total salar1 o, t3e de$artment to 3ic3 t3e ne em$lo1ee 3as 0een assi"ned. 4unnin" 4esult Typ

$5L! DE$C %* r7tri'' r* Nam N%llY """"""""""""""""""""""""""" """""""" """"""""""""""""""""""""" TRIGGER7NA2E 3ARC/AR-(91) TRIGGER7TDPE 3ARC/AR-(0H) TRIGGERING7E3ENT 3ARC/AR-(--G) TABLE7O:NER

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%%

3ARC/AR-(91) BA$E7OBQECT7TDPE 3ARC/AR-(0H) TABLE7NA2E 3ARC/AR-(91) COL,2N7NA2E 3ARC/AR-(<111) RE8ERENCING7NA2E$ 3ARC/AR-(0-L) :/EN7CLA,$E 3ARC/AR-(<111) $TAT,$ 3ARC/AR-(L) DE$CRIPTION 3ARC/AR-(<111) ACTION7TDPE 3ARC/AR-(00) TRIGGER7BODD $5L! ta&l 9

LONG

$ELECT tri'' r7nam . tri'' r7typ . tri'' rin'7 E nt. 7nam 8RO2 %* r7tri'' r* :/ERE ta&l 7oMn r ; 4$NO:BALL4 ;

TRIGGER7NA2E TRIGGER7TDPE TRIGGERING7E3ENT TABLE7NA2E """""""""""" """"""""""""" """"""""""""""""" """""""""""" NE:7E2P7DEPT IN$TEAD O8 IN$ERT OR ,PDATE OR DELETE E2P7DETAIL$ $5L! IN$ERT INTO mp7d tail*( mpno. nam . *al. d ptno. 6o&) - 3AL,E$(N110.4ABBOTT4.9111.01.4/R72AN4); 0 roM (r at d@ $5L! $ELECT mpno. nam . d ptno. 6o& 8RO2 E2PNO ENA2E DEPTNO QOB """"""""" """""""""" """"""""" """"""""" GGL- CLARO 01 2ANAGER mp7d tail* ;

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%6

GL9N OING GN9< 2ILLER GGL- CLARO GL9N OING GN9< 2ILLER GGL- CLARO GL9N OING GN9< 2ILLER G9HN $2IT/ GLGH ADA2$ GN1- 8ORD GGLL $COTT GJHH QONE$ G<NN ALLEN GHNL BLAOE GHJ< 2ARTIN GN11 QA2E$ GL<< T,RNER GJ-0 :ARD -1 roM* * l (t d@

01 01 01 01 01 01 01 01 -1 -1 -1 -1 -1 91 91 91 91 91 91

PRE$IDENT CLERO 2ANAGER PRE$IDENT CLERO 2ANAGER PRE$IDENT CLERO CLERO CLERO ANALD$T ANALD$T 2ANAGER $ALE$2AN 2ANAGER $ALE$2AN CLERO $ALE$2AN $ALE$2AN

$5L! $ELECT mpno. nam . *al. d ptno 8RO2 n M7 mp* ; E2PNO ENA2E $AL DEPTNO """"""""" """""""""" """""""""" """""""""" G9HN $2IT/ L11 -1 G<NN ALLEN 0H11 91 = GN9< 2ILLER 0911 01 N110 ABBOTT 9111 01 0J roM* * l (t d@ $5L! $ELECT d ptno. dnam . tot7d pt7*al 8RO2 n M7d pt* ; DEPTNO DNA2E TOT7DEPT7$AL """""""""" """""""""""""" """""""""""" 01 ACCO,NTING 9J-J1 -1 RE$EARC/ 01LGJ 91 $ALE$ N<11

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%7

$5L! $/O: rror* tri'' r n M7 mp7d pt No rror*@ Differentiating Bet-een Database *riggers and Stored Procedures (ri""ers De,ined it3 CREATE TRIGGER Data dictionar1 contains source code in ,$ER7TRIGGER$ Procedures De,ined it3 CREATE PROCED,RE Data dictionar1 contains source code in ,$ER7$O,RCE *5$licitl1 invo.ed CO22IT? $A3EPOINT? and ROLLBACO are allo ed

Im$licitl1 invo.ed CO22IT? $A3EPOINT? and ROLLBACO are not allo ed

'anaging )rigger Displaying *rigger Definition #rrors +s ,or PL2SQL $rocedures? i, 1ou "et a messa"e :arnin'= Tri'' r (r at d Mith (ompilation 1ou can see t3e error messa"es 01 t1$in" $/O: ERROR$ TRIGGER <tri'' r7nam !; .ie-ing Defined *riggers (o vie a list o, all de,ined tri""ers? use: $ELECT tri'' r7nam 8RO2 %* r7tri'' r*; For more details on a $articular tri""er:

rror*@

$ELECT tri'' r7typ . tri'' rin'7 E nt. ta&l 7nam . r ) r n(in'7nam *. tri'' r7&ody 8RO2 %* r7tri'' r* :/ERE tri'' r7nam ; 4<tri'' r7nam !4; Dropping *riggers (o dro$ a tri""er: DROP TRIGGER <tri'' r7nam !; Disabling *riggers (o disa0le or ena0le a tri""er: ALTER TRIGGER <tri'' r7nam ! Rdi*a&l # na&l S >ALL TRIGGER$?;

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%'

!ecompile a trigger for a table, ALTER TRIGGER tri'' r7nam CO2PILE

Aborting *riggers -it #rror (ri""ers can o,ten 0e used to en,orce constraints. (3e :/EN clause or 0od1 o, t3e tri""er can c3ec. ,or t3e violation o, certain conditions and si"nal an error accordin"l1 usin" t3e Oracle 0uilt>in ,unction RAI$E7APPLICATION7ERROR. (3e action t3at activated t3e tri""er Dinsert? u$date? or deleteF ould 0e a0orted. For e5am$le? t3e ,ollo in" tri""er en,orces t3e constraint Person.a"e JI -: CREATE TABLE P r*on (a' int);

CREATE TRIGGER P r*onCh (BA' A8TER IN$ERT OR ,PDATE O8 a' ON P r*on 8OR EAC/ RO: BEGIN I8 (=n M@a' < 1) T/EN RAI$E7APPLICATION7ERROR("-1111. 4no n 'atiE alloM d4); END I8; END; I, e attem$ted to e5ecute t3e insertion: in* rt into P r*on Eal% * ("9); e ould "et t3e error messa"e: ERROR at lin 0= ORA"-1111= no n 'atiE a' alloM d ORA"1HJ0-= at P2DNA2E@PER$ONC/ECOAGEP. lin 9 ORA"1<1LL= rror d%rin' + (%tion o) tri'' r 42DNA2E@PER$ONC/ECOAGE4

a'

&ot3in" ould 0e inserted. In "eneral? t3e e,,ects o, 0ot3 t3e tri""er and t3e tri""erin" statement are rolled 0ac.. *5ecutin" *5am$les

$5L! CREATE TABLE T< (a INTEGER. & C/AR(01)); Ta&l (r at d@ $5L! CREATE TABLE TJ (( C/AR(01). d INTEGER); Ta&l (r at d@

DBMS Unit 4

Procedural SQL Fundamentals: Part II

%)

$5L! CREATE TRIGGER tri'0 A8TER IN$ERT ON T< 9 RE8ERENCING NE: A$ n MRoM < 8OR EAC/ RO: J :/EN (n MRoM@a <; 01) H BEGIN G IN$ERT INTO TJ 3AL,E$(=n MRoM@&. =n MRoM@a); L END tri'0; N A Tri'' r (r at d $5L! IN$ERT INTO T< 3AL,E$ (0. 4aaa4); 0 roM (r at d@ $5L! IN$ERT INTO T< 3AL,E$ (00. 4&&&4); 0 roM (r at d@ $5L! $ELECT F 8RO2 tJ; C D """""""""""""""""""" """""""""" aaa 0 $5L! IN$ERT INTO T< 3AL,E$ (00. 4&&&4); 0 roM (r at d@ $5L! $ELECT F 8RO2 tJ; C D """""""""""""""""""" """""""""" aaa 0 $5L! *hoM rror* tri'' r tri'0; No rror*@ $5L! $ELECT tri'' r7nam . tri'' r7typ . r ) r n(in'7nam *. *tat%*. tri'' r7&ody 8RO2 %* r7tri'' r*;

DBMS Unit 4

Procedural SQL Fundamentals: Part II

6-

TRIGGER7NA2E TABLE7NA2E TRIGGER7TDPE RE8ERENCING7NA2E$ $TAT,$ """"""""""" """"""""""" """"""""""""""""""""""""""""" """""""""" TRIGGER7BODD """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" TRIG0 T< A8TER EAC/ RO: RE8ERENCING NE: A$ NE:RO: OLD A$ OLD ENABLED BEGIN IN$ERT INTO TJ 3AL,E$(=n MRoM@&. =n MRoM@a); END tri'0; $5L! ALTER TRIGGER tri'0 DI$ABLE; Tri'' r alt r d@ $5L! $ELECT tri'' r7nam . ta&l 7nam . *tat%* 8RO2 %* r7tri'' r*; TRIGGER7NA2E TABLE7NA2E $TAT,$ """"""""""""""" """"""""""" """"""""" TRIG0 T< DI$ABLED $5L! DROP TRIGGER tri'0; Tri'' r dropp d@ $5L! CREATE TABLE p r*on (a' Ta&l (r at d@ int);

$5L! CREATE TRIGGER p r*onCh (BA' - A8TER IN$ERT OR ,PDATE O8 a' ON p r*on 9 8OR EAC/ RO: < BEGIN J I8 (=n M@a' < 1) T/EN H RAI$E7APPLICATION7ERROR("-1111. 4no n 'atiE alloM d4); G END I8; L END;

a'

DBMS Unit 4

Procedural SQL Fundamentals: Part II

61

N A Tri'' r (r at d $5L! IN$ERT INTO p r*on 3AL,E$ ("9); IN$ERT INTO p r*on 3AL,E$ ("9) F ERROR at lin 0= ORA"-1111= no n 'atiE a' alloM d ORA"1HJ0-= at P$NO:BALL@PER$ONC/ECOAGEP. lin ORA"1<1LL= rror d%rin' + (%tion o) tri'' r 4$NO:BALL@PER$ONC/ECOAGE4

Vous aimerez peut-être aussi