Programming Oracle Triggers and Stored Procedures [3 ed.] 9780130869852, 0130869856

Advanced Oracle features such as triggers and stored procedures make itpossible to build databases that incorporate busi

315 116 5MB

English Pages 446 Year 2003

Report DMCA / Copyright

DOWNLOAD PDF FILE

Recommend Papers

Programming Oracle Triggers and Stored Procedures [3 ed.]
 9780130869852, 0130869856

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Copy right

Ef fectAbout ivelyPrent creat anProf d man ageTechnical com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t iceeHall essional Reference KevinPref Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ace t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Who Will Ben efit f rom Th is Book?

How I s This Bo ok Str uct ur ed? Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Conevent adv ant ag of ion Orsacle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Ack nowledgmen ts at e bu siness r ules w hich ar e easy t o man age and m odif y as t he dat ab ases t o incor por bu sin ess evolv es.AnTopics cov include: Cha pter One. I nt ro duct ioner t oed Relat ional Da tab ase Tables Section 1 .1 . Before Relat ion al Tables Section 1 .2 . SQL

View in g const r aint s in t h e dat a dict ion ar y Section 1 .3 . Tables Section . SQL St orcem at emen ts Com plex1 .4r ule enf en t Section 1 .5 . Table Colum n Dat at ypes

PL/ SQL p r ogr am un it s and langu age f eat u res Section 1 .6 . Behind Tables Cha pter Two. I nt eract ing wit h Oracle

Dat a t y pes and comp osit e st r u ct u re Section 2 .1 . Simplif y SQL* Plu s f or Yourself on Windows 2 .2dling . Con nect ErSection r or han andingexcept ions Section 2 .3 . Con nect ing t o an I n frastr uct ur e

I ntSection er - pr 2ocess com mu nicat ions .4 . Disconn ect in g Section 2 .5 . Com m and Line

Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m Section or e 2 .6 . Ch anges on th e Com ma nd Line Section 2 .7 . Script s

Pr ogr am m ing2Oracle igger Section .8 . ScriptTrOu tp ut s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, esign er s, pr oj ect leader s look in g t o b uild an d m aint ain t r uly Section 2 .9 . Com m and d Line Arg um en tand s int ellig en t , com plex dat abases. Section 2 .1 0. SQL* Plus wit h Korn Shell Section 2 .1 1. Bat ch Com m and Files

[ Team LiB ]

Section 2 .1 2. SQL* Plus wit h Act ive St at e Perl Section 2 .1 3. Privileges Section 2 .1 4. DUAL

[ Team Section LiB ]

2 .1 5. Au t otr ace

Cha pter Thr ee. Declarat iv e Con st raint s Section 3 .1 . Prim ary Key Section 3 .2 . UNI QUE Section 3 .3 . Foreign Key Section 3 .4 . Ch eck Section 3 .5 . NOT NULL Constr aint s Section 3 .6 . Defau lt Values Section 3 .7 . Modifying Const rain t s Section 3 .8 . Except ion Han dling Section 3 .9 . Dat a Loads Cha pter Four. A Dat a Model wit h Const rain ts Section 4 .1 . Ent it y Relation ship Diag ram Section 4 .2 . Table Descript ion s



Content s SectionTable 4 .3 . of DDL Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on Section 4 .4 . Sam ple Data By KevinCha Owens pter Five. Viewing Const ra in t s in t he Dat a Diction ary Section 5 .1 . Wh at You Can See Section 5 .2 . Dict ionary Views: An Ov erv iew Pub lish er: Prent ice Hall PTR Section 5 .3 . Con st raint Views Pub Dat e: Decem ber 0 5, 2 003 Section 5 .4 . USER_CONS_COLUMNS I SBN: 0- 13 -0 850 33 -0 Section 5 .5 . USER_CONSTRAI NTS Pages: 44 8 Section 5 .6 . Dat a Dict ionar y Const ra in t Script s Cha pter Six . Row Trigger Mech anics Section 6 .1 . I n t roduct ion Section 6 .2 .e Before versus Af t ercom plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Ef fect ively creat an d man age Section .3 .plor I n sert Trigger Or Sy acle's nt ax Kevin Ow ens 6ex es Row PL/ SQL, answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eachesSection you w6 .4 hat . Trigger y ou nBody eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Section 6 .5 . Exam ple Row Triggers

Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Section 6 .6 . A Table wit h Oracle Const rain t s an d Busin ess Ru les adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Cha pter Sev en. Stat em en t Lev el Tr ig ger s dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he Section 7 .1 . Sequence of Ev ent s bu sin ess evolv es. Topics cov er ed include: Section 7 .2 . I n sert St at em ent Trigger Sy nt ax Section 7 .3 . St at em ent Lev el Agg reg ation

View in g 7const aint s in t hCapt e dat a Dat dicta ion ar y Section .4 . Pror cessing Row u red Cha pter Eigh t. Com plex Rule Enf orcemen t

Com plex r ule enf orcem en t

Cha pter Nin e. The PL/ SQL En vir onm en t Section 9 .1 . A am Helloun World Program PL/ SQL p r ogr it s and langu age f eat u res Section 9 .2 . Ref eren cing Ora cle Pack ages

Dat a t y pes comp osit e st r u ct u re Section 9 .3 . and USER_OBJECTS Section 9 .4 . Depen dencies amon g Pr oced ures

Er r or han dling and except ions Section 9 .5 . USER_DEPENDENCI ES

.6 . USER_SOURCE I ntSection er - pr 9ocess com mu nicat ions Section 9 .7 . Shar in g Co de

Declar at9iv r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Section .8e . const Com pilat ion Dependency m Section or e 9 .9 . USER_ERRORS Cha pter Ten. PL/ SQL Progr am Un it s Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Section d 1 0. Procedures for dat abase ev1.elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Section 1 0. 2. Fu nct int ellig en t , com plex dations abases. Section 1 0. 3. Su bprogram Enca psulat ion: I n t roduction t o Packages

[ Team Section LiB ]

1 0. 4. Pack age Specificat ion

Section 1 0. 5. Package Body Section 1 0. 6. Applicat ion Part it ionin g Section 1 0. 7. Dat a Abst ract ion

[ Team Section LiB ]

1 0. 8. Param et ers and Modes

Section 1 0. 9. Ov erloading Cha pter Elev en . PL/ SQL Lan guage Feat ur es Section 1 1. 1. Comm ent s Section 1 1. 2. Assig nm en t s an d St at em ent s Section 1 1. 3. Boolean Expr ession Section 1 1. 4. Ex pressions wit h NULL Section 1 1. 5. Logical Operat or s Section 1 1. 6. St rin g Con cat enat ion Section 1 1. 7. Arit h met ic Exp ressions Section 1 1. 8. Var ia ble Declara tion s Section 1 1. 9. Typ es Section 1 1. 10. I F St at ement Section 1 1. 11. CASE St at ement



Content s SectionTable 1 1. 12.of LOOP Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on Section 1 1. 13. STRI NG Manipu lat ion Fu nct ions By Kevin Owens Section 1 1. 14. Miscellaneou s St ring Function s Section 1 1. 15. Nu meric Funct ion s Section 1 1. 16. Ran dom Nu mber Gen era tion Pub lish er: Prent ice Hall PTR Section 1 1. 17. Dat e Function s Pub Dat e: Decem ber 0 5, 2 003 Section 1 1. 18. Ex cept ions I SBN: 0- 13 -0 850 33 -0 Section 1 1. 19. Dat abase Access with SQL Pages: 44 8 Section 1 1. 20. Sen ding Pipe Messa ges ( DBMS_PI PE) Section 1 1. 21. Signaling Event s with Alert s ( DBMS_ ALERT) Section 1 1. 22. Em ail Not ificat ion wit h Triggers an d Alert s

[EfTeam LiBcreat ] fect ively e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Copyright Li bra r y of Cong re ss Ca t al ogi ng- in- Pu bli cat i on Da t a

Ow ens, Kevin . Pr ogr am min g Oracle t r igger s and st or ed p rocedur es / Kev in Ow en s. p. cm . I SBN 0- 1 3- 08 503 3- 0 1. Or acle ( Comp ut er f ile) 2. Relat ional dat abases. 3. Comp ut er soft w ar e- - Developm ent . I . Tit le. • Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

QA76 . 9. D3O97 200 4

By00 Kevin Owens 5. 75' 85 - - dc22

20 030 2368 5 Pub lish Prent Ed iter: orial/ price odHall uctPTR ion

sup er v ision : Jessica Balch ( Pine Tr ee Com posit ion, I nc. )

Pub Dat e: Decem ber 0 5, 2 003

Cov er 0desig n direct I SBN: 13 -0 850 33 -0 or : Jer r y Vot t a Pages: 44 8

Cov er desig n: Ant hon y Gem mellaro Ar t d ir ect or : Gail Cock er - Bogusz Ef fectMan ivelyufact creat an m d anag man age com is plex ureing er : Alex Heydat dt abases - Long w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d Pubyou lisher : Jefyfou Pep per t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. t eaches w hat n eed UsingEd easyt o-assist followant inst uct ions anagn d exano am ples, t his book pr esent s t echniq ues t o t ake it orial : rLinda Ram adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our g m an ager: Robin O' rBr ien w hich ar e easy t o man age and m odif y as t he dat abMar asesk et t oinincor por at e bu siness ules bu sin ess evolv es. Topics cov er ed include: Full- ser v ice p rod uct ion man ager: Ann e R. Garcia © 200View 4 Pear Educat in gson const r aint sion, in tIhnec.dat a dict ion ar y Pub lishin as Prent Hall Pren ofession al Tech nical Refer ence Comgplex r ule ice enf orcem t UpperPL/ Sadd eram , NJun074 SQLlepRiv r ogr it s 58 and langu age f eat u res Pr en t ice PTRand of fercomp s excellent Dat Hall a t y pes osit e stdiscount r u ct u re s on t his book w h en or der ed in quan t it y for bulk pu rchases or special sales. For m or e infor m at ion, please cont act : Er r or han dling and except ions U.S. Cor por at e and Gov er nm en t Sales 1- 8 00I nt 3 82er - pr 3 419 ocess com mu nicat ions corp sales@pear son t ech gr oup. com Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch For sales m or eou t sid e of t he U. S. , please con t act : IPrntogr er nat amional m ing Sales Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce 1- 3 175 81- 3 793 for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig er naten ional@p t , com plex ear sont datechgr abases. oup .com [OtTeam h er com LiBpan ] y and pr odu ct nam es m ent ioned herein are t he t r adem ar ks or r eg ist er ed t r adem ark s of t h eir r espect iv e ow ner s. All r ight s reserv ed. No par t of t h is book m ay b e repr od uced , in an y for m or by an y means,

w hout LiB per m [ it Team ] ission in w r it ing fr om t h e pu blish er . Pr int ed in t h e Un it ed St at es of Am erica First Prin t in g Pearson Pearson Pearson Pearson Pearson Pearson Pearson Pearson

Ed ucat ion Lt d. , London Ed ucat ion Au st ralia Pt y, Lim it ed, Syd ney Ed ucat ion Sin gapor e, Pt e. Lt d . Ed ucat ion Nor t h Asia Lt d . , Hong Kong Ed ucat ion Canada, Lt d. , Tor on t o Ed ucación de Mex ico, S. A. de C.V. Ed ucat ion–Jap an, Tok y o Ed ucat ion Malay sia, Pt e. Lt d.

[• Team LiB ] Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

About Prentice Hall Professional Technical Reference Wit h or ig ins r each in g back t o t he indu st ry ' s fir st com put er scien ce pub lishing p rog ram in t h e 19 605 , and for m ally launched as it s ow n im pr in t in 19 86, Prent ice Hall Pr of ession al Technical Refer ence ( PH PTR) has developed in t o t h e lead ing pr ov id er of t echn ical book s in t he w or ld t oday . Our edit or s now pub lish ov er 200 book s an nually , aut h ored by leader s in t he fields of com put ing , engin eer in g, an d business. fir moflyContent plant ed •Ou r r oot s ar e Table s in t he soil t hat gav e r ise t o t h e t ech nical r ev olut ion. Our book shelf con t h eStor indu ry 's dure coms,pThir ut ing and Pr ogr am m ing Ortaains cl e ® m Tr any i ggerof s and e d st P roce d Edi ti onengin eer in g classics: Ker nigh an an d Rit chie's C Pr ogram m in g Language , Nem et h 's UNI X Sy st em Adm in ist r at ion Han dbook , By Kevin Owens Hor st man n's Cor e Jav a , an d Joh nson' s High - Speed Digit al Design . Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

PH PTR ack now led ges it s auspicious b eg in ning s w hile it look s t o t he f ut ur e f or inspir at ion. We Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t cont inu e t o ev olve an d br eak n ew gr oun d in pu blish ing by pr ov iding t oday ' s pr ofession als Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d w it h t om orr ow 's solu t ions. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake [ Team LiB ] adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Preface This b ook emp hasizes cor e concept s of t h e Or acle D at abase Serv er : dat abase t ables, index es, t ablespaces, const r aint s, t r igg er s, and PL/ SQL. Mast er ing t hese core com pon en t s is essent ial t o applicat ions dev elop ment . Whet her y ou ar e a w eb developer or a client / serv er or b ack end pr ogr am m er , t he cont ent in t his book w ill h elp y ou r ealize t he p ot en t ial of im plement in g log ic in t he d at abase ser v er w it h d eclar at ive an d pr ocedu ral con st rain t s, using PL/ SQL t r igger s and st or ed pr ocedur es. [ Team LiB ] •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Who Will Benefit from This Book? This is a pr ogr am m er ' s book . Som e pr ogr am m ing kn ow ledg e is helpf ul b ut n ot essen t ial. No pr ior k now ledge of Oracle is r equir ed . Dev eloper s t r ansit ioning f rom ot her dat ab ases t o an Or acle en vir onm ent can b en ef it f rom t he d et ailed ex planat ion s, num er ous f ig ur es, an d man y code ex amp les t hat illust r at e Or acle st ru ct ur es. Th e discu ssion on t r ig gers and PL/ SQL is gear ed t ow ar d an in div id ual w h o w ant s a qu ick t ran sit ion fr om ot her pr ogr am m in g par adig ms t o t h e PL/ SQL m odel. I h ave wor k ed on Or acle pr oject s st aff ed w it h non - Or acle dat ab ase developer s and un derst and t h e confu sion w it h t erm inology . A consist ent focus of t his t ex t is t o ex plain t h e basic par adig m, w hich h elps reader s w ho are new t o t he t echnology as w ell as exp er ienced d ev elop er s w h o ar e cr oss- t r aining . •

Table of Content s

Pr ogr am a cl e ®developer Tr i gger s and de P roce s, Thirgd fEdi ti on This t exmt ing canOrhelp s wStor ho ear t r andure sit ionin r om non - relat ional

d at abases t o Oracle. Ch apt erOwens 1 ad dr esses t he b eg inning s of SQL. Developer s fr om h ier ar ch ical and net w or k By Kevin dat ab ases w ill f ind t his chap t er a place in w hich t h at t h ey can pu t SQL in t o per spect iv e. The early p ar t of m y car eer included fiv e y ear s on a hierar chical dat ab ase and t hr ee year s on a net w orlish k dat ab ase. I und Pub er: Prent ice Hall PTR er st and t he t ran sit ion needed t o sw it ch t o Or acle, an d t he exp lanat ions in t his ex2t003 sh ould addr ess t he needs of n on- r elat ion al dev eloper s w ho are Pub Dat e: Decem ber 0t 5, cross- tIrSBN: aining . 0- 13 -0 850 33 -0 Pages: 44 8 Dev eloper s w ho nat u rally " d ig " int o a su bject w ill b en ef it f rom t he d iscussion on t he Or acle dat a dict ionar y , addr essed ex t ensiv ely in Ch apt er 5. Th is ch apt er illust rat es ex t r act in g const r ain t d ef init ions f r om t he d at a d ict ion ary . A cu r iou s dev eloper can exp and t his simp le t echniqu e t o ex t r act un lim it ed in for m at ion f r om t he dat a dict ion ary . Th is is high ly beneficial man age abases w ithav h Oreacle! st ems and tEf o fect anxively iou s creat lear neeran s. dReader s ofcom t he plex p r evdat ious edit ions m en tSy ioned t h is as dat oneabofase t heexmper ostt KevinulOw ens ex tplor PL/becau SQL, se Or acle's answ er t ohow t h e tSt uct ur ed Query Langu SQL) helpf p art s of he besook it t au ght t hem o rex plor e and learn on tage heir (ow n. , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Dev eloper s of t en f in d t hem selves p er f orm ing dat abase adm inist rat ion —usually on a Using easyt o-ser follow ex am pr esent s t dat echniq uesad t omt in ake dev elop ment v er . inst Th isr uct t extions is aan gd ood st arples, t ing pt his oin book t f or begin ning ab ase ist r at ion. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat allow y our Dev eloper s ar e nat u r ally in t ouch w it h t he logical w or ld of t ables and t ablesp aces. The dat ab ases ton o incor at e bu sinesss rofules hich ar e easy t o man age m odif ascellent t he discussion t he ppor hy sical aspect t hewdat abase, t ab lespace dat aand files, is any ex buar sin esspoint evolvfor es. aTopics cov erwed st t ing dev eloper h oinclude: needs t o un derst and t h e phy sical asp ect s of an Oracle env iron ment .

in gt hconst r aint s inont hbuilding e dat a dict ion ess ar y logic in an Or acle dat abase. A con sist ent ForemView ost is e emp hasis bu sin t hem e in t he t ex t is t o m ak e t he d at abase w or k for y ou. An ap plicat ion t eam t h at capit alizes Comat plex ule enf orcem enpr t oduce an " int elligent " dat abase in w hich all dat a conf or m s t o on declar iv e rconst r ain t s can st r ict business- r u le log ic. Fu rt h er m or e, w hen t he t eam incor por at es t r igger s w it h PL/ SQL, t he PL/ SQL p r ogr am un it s and langu age f eat u res dat ab ase in t egr it y ex t end s t o a point w her e it can perf or m logical oper at ions on t h e en duser' sDat b eh This cancomp include bu sin ess- r ule enfor cem ent as w ell as act ions such as a alf t y .pes and osit ecom st r uplex ct u re aut om at ic em ail not if icat ion , w hich is illust r at ed in Ch apt er 11 . Er r or han dling and except ions [ Team LiB ] I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

How Is This Book Structured? Chapters 1 and 2 Ch apt ers 1 an d 2 cov er Or acle t ables, colum n t y pes, and how t o use SQL* Plus t o int er act w it h t he d at abase. Some highly u sef ul f eat ur es of SQL* Plus are descr ibed in clud ing SQL* Plu s com man ds t o sh ow a SQL ex ecu t ion plan an d it s st at ist ics. These chapt er s concen t r at e on t er min olog y, ex plaining t h e int uit iv e m eaning of t he t er m s SQL, SQL* Plus, and PL/ SQL. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Chapters 3,4, and 5 By Kevin Owens

Ch apt ers 3, 4, an d 5 t hor ough ly cov er declarat iv e const r aint s includ in g ex t r act in g con st r aint defin it ion s fr om t he Or acle dat a dict ionar y. These ch apt ers ( a) p rov ide y ou w it h t he Pub lish er: Prent ice Hall PTR k now led ge t o build a d at abase w it h high int egr it y —som et hin g ev er y clien t w an t s, ( b) Decem ber 0 5, 2 003 empPub owDat er e:you w it h t he sk ill t o ex t r act a w ide var iet y of infor m at ion fr om t h e dat a I SBN: 0- 13 -0 one need s, and ( c) pr ov ide insight int o declar at iv e const r ain t s and dict ionar y —a sk-0ill850 ev33ery Pages: 8 st an d h ow t h ey w or k . help you un 44 der

Chapters 6,7, and 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d Ch apt ers 6, 7, an d 8 cov er dat ab ase t rigg er s, also called pr ocedur al const r aint s. Ch apt ers 6 t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. and 7 p r ovide an in t uit ive und er st andin g w it h nu m er ous f igur es t o illu st r at e t able r ow and st at ement t r igg er s. rThis in t uit und st and in gbook is cr itpr ical in hs elp in g you Using easy-level t o- follow inst uct ions anive d ex amerples, t his esent t echniq ueschoose t o t akew hat apt er gers 8 illust r atstes t he pr use of ur dat abase iggt hat er s an d y our tadv y peant ofag t r igg e. Chas e oferOryou acleshould feat ur w esr itsuch t rig and ored oced esf eat utrres allow PL/ SQL f or com plex ru le en for cem ent . dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

Chapter 9

View in g const r aint s in t h e dat a dict ion ar y

Ch aptCom er 9 plex h elp rsule y ouenf g et st ar en t edt qu ick ly w it h com piling PL/ SQL pr ogr am s. A r apid lear ning orcem app roach is t o cod e w hile you lear n. This ch apt er helps y ou und er st and t h e PL/ SQL coding env iron er am comun plet chap t erf eat , y ou w ill hav e a b asic u nder st andin g of h ow t o PL/ment SQL .pAft r ogr it s ing andt his langu age u res code, com pile, an d ex ecu t e PL/ SQL p r ocedu res. The f ollow in g t wo chapt er s pr ov ide t h e t echnical Dat acont t y pes ent and of PL/ comp SQLosit w hile e st rt uh ct isuch reapt er int r od uces t he m eans t o cod e and t est as y ou learn . Er r or han dling and except ions I nt er - pr ocess com mu nicat ions

Chapter 10

Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch e look s at PL/ SQL f r om a soft war e eng ineer ing per sp ect iv e. I t is not enoug h just t o Ch aptm eror10 k now t h e PL/ SQL sy nt ax . Befor e a langu age bear s m ean ing, one needs t o und er st and t h e Pr ogr ampmaring Oracle andf or St or edSQL Pr oced es , unit Th irs: d Ed it ion , is an e, invf unct aluable esou rce PL/ SQL adigm an dTrt igger he msodel PL/ p rogurr am t he p rocedur ion, rand for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain pack age. This chap t er t each es y ou PL/ SQL p r ogr am un it s con cept ually and encour agest ryuly ou t o ellig en t , com plex dathow abases. tint hin k about w hen and t o use t h ese p rog ram unit s dur ing t he d esign ph ase. [ Team LiB ]

Chapter 11

Ch apt er LiB 11 ]cov ers PL/ SQL langu age f eat ur es. Par t icular at t ent ion is g iv en t o PL/ SQL [ Team const r uct s and bu ilt - in SQL f unct ions, em ph asizing w r it ing sim ple an d easy - t o- und er st and algor it hm s. The ch apt er conclu des w it h a sect ion t hat illust rat es an ap plicat ion using a dat ab ase t r ig ger t o send em ail not ificat ion using t he Oracle bu ilt - in Alert s pack age. All script s in t he t ex t w ere ru n ag ainst Oracle 9i Release 2 and 10g Ver sion 1 0. 1. 0. [ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Conventions The u se of upp er and low er case is int end ed t o mak e clear t he ident it y of SQL and PL/ SQL k ey w or ds. All SQL and PL/ SQL cod e is w r it t en in low er case except for lan guag e key w ord s, w hich are u pper case. The f ollow ing , t ak en f r om Ch apt er 3, illust r at es t his w r it ing st yle.

CREATE SEQUENCE student_vehicles_pk_seq; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Qu ot edOwens ex pr essions ar e oft en in upp er case as w ell as all r efer ences t o Or acle built - in By Kevin fu nct ions. The follow in g, t aken fr om Ch apt er 11 , includ es refer ences t o t w o Or acle b uilt - in fu nct ions ( NEWTI ME and SYSDATE) w rit t en in u pper case. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

pst_date := NEW_TIME(SYSDATE, 'EST','PST');

Or acleively pr ovid es emay uilt - in es. Th samp lewcod t his Sy t ext r efers all ab b uilt Ef fect creat an dbman agepackag com plex dateabases it h eOrinacle! st ems andt odat ase- in ex per t pack in low This decision w as m ade t heurcode m or e Langu r ead able easier Kevinages Ow ens ex er plorcase. es PL/ SQL, Or acle's answ er t ot ot hmeake St r uct ed Query age and ( SQL) , an d on t he eyyou es. w Excessiv pert ocase t ex can berob rou ghan ond com t he cor neas. The f ollow , frbom t eaches hat y ouenup eed kn ow t ot build ust plex dat ab ases f or ing y our usiness. Ch apt er 11 , illust r at es t he choice of low er case w hen w r it in g refer ences t o t h e Or acle b uilt - in Usingage easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake pack DBMS_ALERT. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y dbms_alert.register('OUT_OF_STOCK_ITEM'); Com plex r ule enf orcem en t The PL/ SQL code ex amp les of t en in clud e count er v ar iable declarat ion s; t hese ar e oft en in SQLTh p reogr am un it sfrand langu f eat res es a v ariab le, I D. This is not a k eyw or d up perPL/ case. follow ing, om Ch aptage er 11 , d ueclar bu t is easier t o r ead in up per case. Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions ID

VARCHAR2(10), Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e

Finally code t ex t ,Trt igger hat is, t h e par s of ur t he ayit sion r ef, ers code it em sr esou in upp Pr ogr amnonm ing Oracle s and St oragr ed aph Pr oced es t, ex Tht ,ir alw d Ed is ant oinv aluable rceer case. Th e t ext of a p arag r aph may ref er t o a con st r aint nam e or PL/ SQL v ariab le nam e, and for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly alwellig ays,ent he code ident ier is wr it t en in u pper case w it hin t he b ody of a par agr aph. int t , com plex datifabases. [[ Team Team LiB LiB ]]

[ Team LiB ]

Acknowledgments I w ould like t o t h ank t h e t ech nical r ev iew and edit ing t eam: Pat St arr , Kat hr yn Ty ser , an d Lin da Owens. Th ank s also t o Jef fr ey Pepper at Pr en t ice Hall f or diligence, and t h e t hor oug h edit ing fr om copy edit or Laur a Bu rg ess, and Jessica Balch at Pine Tree Comp osit ion. Kevin Ow en s [ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Chapter One. An Introduction to Relational Database Tables 1. 1 BEFORE RELATI ONAL TABLES 1. 2 SQL 1. 2. 1 ANSI St and ar d •

1.Table 2. 2 SQL Dat absase of Content

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

1. 2. 3 SQL I m plem ent at ion

By Kevin Owens

1. 2. 4 SQL* Plus Pub er: Prent ice Hall PTR 1.lish 3 TABLES Pub Dat e: Decem ber 0 5, 2 003

Dat I SBN:1.0-3. 131-0 850a33Model -0

View

Pages: 44 8

1. 3. 2 Cr eat e Table Scr ipt 1. 3. 3 Descr ibing t h e Table

Ef fect ively 1. creat 3. 4 e Table an d D man at aage com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 1. 4you SQL wSTATEMENTS t eaches hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 4. 1follow Dat a inst Definit Lan e ( DDL) Using easy-1.t or uction ions anguag d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 2 Datpor a Manip ion rLangu dat ab ases 1. t o4.incor at e buulat siness ules wage hich( DarML) e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: 1. 4. 3 Tr ansact ion Cont r ol 1.g4.const 4 Session r ol View in r aint sCont in t h e dat a dict ion ar y 1. 4. 5r ule Sy stenf emorcem Cont en r olt Com plex 1. TABLE COLUMN PL/5 SQL p r ogr am unDATATYPES it s and langu age f eat u res 1 Ch aract er osit e st r u ct u re Dat a 1. t y 5. pes and comp 5. 2dling Num and ber except ions Er r or 1. han 3 DATE Tymu pes I nt er -1. pr5. ocess com nicat ions ge Obj ect Declar1.at5.iv4eLar const r aint s,sincluding p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e 1. 5. 5 XML Ty pe Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce 1. 5. 6 LONG an dd RAW Tys, pes for dat abase d ev elopers, esign er and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. 1. 5. 7 ROWI D Ty pe [ Team LiB ] 1. 6 BEHI ND TABLES 1. 6. 1 App licat ion Tablesp aces

[ Team LiB1.] 6. 2 Dat a Dict ionar y [ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

1.1 Before Relational Tables I n 196 9, Apollo ast r onau t s Neil Ar mst r ong and Bu zz Aldr in walk ed on t h e m oon. Th at sam e y ear Dr . Ed gar Fr ank Cod d, Ph .D ., developed t he t h eor y f or r elat ion al dat ab ase sy st em s. Shor t ly af t er t his dev elop ment , Codd p ublished " A Relat ional Model of Dat a for Lar ge Shar ed Dat a Bank s" in t he Associat ion of Com pu t ing Machiner y ( ACM) jou rn al, Com m un icat ion s of t he ACM. Codd' s m odel becam e t he f ound at ion for a pr ot ot y pe; a r elat ional dat abase p roj ect w it hin I BM called Sy st em / R. St udies w ere perf or med at t he I BM San Jose Research Cent er ( now t he Alm aden Resear ch Cen t er ) and by 1 974 I BM had a r un ning pr ot ot y pe r elat ional dat ab ase sy st em. This syst em w as b ased on mu lt it able qu er ies and m ult iuser access. The m et hod for accessing dat a in Sy st em/ R w as called St r uct u red Eng lish Qu er y Languag e •( SEQUEL) . Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Follow it s r esear ch an d developm ent , I BM released Sy st em / R as a p rot ot yp e. I t w as used By Kevin ing Owens by t he MI T Sloan School of Managem en t an d com m er cial or ganizat ion s w it hin t he m anuf act ur ing and inv en t or y sect or s. The p roj ect dem onst r at ed t h at Cod d' s t heor ies could be appPub liedlishand im plem ent ed in t he r eal w orld , bu t ended in 197 9. er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

The su ccess of Sy st em/ R d id n ot r eceiv e quit e t he sam e at t ent ion t he w or ld gav e t he Ap ollo I SBN: 0- 13 -0 850 33 -0 ast r onaut s on Ju ly 20, 196 9; but , Syst em / R's su ccess cr eat ed a new p arad igm in t he w or ld of 8 inf ormPages: at ion 44 t ech nology —a par adigm t hat d om in at es t he inf or m at ion ag e t o t h is day . Cod d b elieved t hat pr ogr am m er s shou ld b e able t o con t r ol t he ex act d at a u sed t o j oin an d const r uct q ueries f rom mu lt iple independ en t t ab les. Th is was not t he case w it h ex ist in g hier archical an denan et wor k d age at abases. Fordat t hese ot her ap plicat ionabp ase rog ram m er Ef fect ively creat d man com plex abases w itt ech h Ornologies, acle! Sy stan ems and dat ex per t w ould Ow code it hm o navOr igat e t h ransw oughert he y ed accessing d at a rage ecor(ds based Kevin ensanexalgor plor es PL/tSQL, acle's t o dat t h eabase St r uctbur Query Langu SQL) , an d on t he p redef ed ynou avigat iont op kn at hs. soft w ar e ust r equir s ch anged, pr ogr merbsusiness. t eaches you winhat n eed ow As t o build rob an dement com plex dat ab ases f oram y our fr equ en t ly need ed dat abase m odificat ions t o t hese pat h s and new n avigat ion s pat h s needed Using easyt ofollow r uctdevelopm ions an d ent ex am esent t echniq t ake t o be def in ed . The sofinst t w are prples, ocesst his w asbook slowprand imspair ed w ues it h frt o equent adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat allow m eet ing s on dat a access. Codd' s m odel h ad a br oad imp act on t he sof t w are developm enty our datocess. ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he pr bu sin ess evolv es. Topics cov er ed include: Sy st em / R w as im plem ent ed by a gr oup of high ly t alen t ed an d edu cat ed soft w ar e engin eer s. They dem onst r at ed t hat lar ge in for m at ion sy st em s cou ld be built on Codd' s t heor y of m ult iViewen intgt const aint sa in h e ur dat a qdict ar y age. This w as t h e bir t h of SEQUEL. independ ables r and st rt uct ed uerion y langu Thr oug hout t he Syst em / R p roj ect , en gineers openly pub lish ed t heir w or k in t echn ical jour n als plexatrional ule enf orcem en t The p olicy of open pub licat ion is considered t o h ave been a and atCom int ern conf erences. fact or in t h e success of Syst em / R—leading t o t he cr eat ion of m any r elat ional d at abases su ch PL/ SQL p r ogr am un it s and langu age f eat u res as DB2 an d Oracle. Dat a t y pes and comp osit e st r u ct u re I BM p assed con t r ol of t he Sy st em/ R st r uct ur ed quer y langu age t o t he Am erican Nat ional St andEr ard nst it ut e (and ANSIexcept ) , a prions iv at e non pr ofit org anizat ion t hat adm inist er s U. S. v olu nt ar y r ors Ihan dling t echnologies. Becau se of t r ad em ar k law s, t he lang uage was renam ed fr om SEQUEL t o SQL f or " St r uct urered y Lang uage. " Tod I nt - prQuer ocess com mu nicat ionsay SQL is an ANSI st andar d and an I nt er nat ional St and ard s Or gan iz at ion ( I SO) st andar d. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch I n 197 m7, or ae gr oup of en gineers wh o h ad b een follow ing t he Sy st em/ R p roj ect , pr imar ily t hr ou gh pub licat ions, r ecog nized it s pot ent ial an d f or med a com pan y. This comp any , Soft war ev elop m enTrt igger Labors at or ies, as Pr latoced er nam Relat Soft new rcomp any Pr ogr amemDing Oracle and St orwed ur esed , Th ir d ion Ed italion , iswar an e. invThis aluable esou rce dev dat elopabase ed and melopers, ar ket ed dt he f irst com m ercial v ersion a r elat dat abase anagem en t for d ev esign er s, and pr oj ect leaderof s look in gion t oalb uild an d mm aint ain t r uly syst emen , wt ,hich on t he ANSI SQL St andar d. They nam ed t heir pr oduct Or acle. int ellig comwas plexbased dat abases. When oject [ TeamprLiB ] Sy st em/ R end ed in 197 9, m any in for m at ion sy st em s r elied on eit h er hier archical or net w ork d at abase ar chit ect u re. I n t he 198 0s, m any dev elop ment pr oj ect s m oved t ow ar d relat ional t echn olog y. Today , t he maj or it y of new inf orm at ion syst em s ar e r elat ion al; how ev er , h ier ar ch ical and net w ork dat abase p rod uct s hav e st ill m aint ained a

m ar ket pr [ Team LiBesence. ] I MS/ DB is t he f lagship hier ar chical dat ab ase of I BM. Rockw ell I nt er nat ional and I BM dev elop ed I MS in 19 69 t o m an age dat a for t he Nat ional Aer onau t ics and Space Adm inist r at ion's ( NASA's) Ap ollo pr ogr am . I MS/ DB con t inues t od ay w it h a solid int er nat ional pr esence. I t is in dust r y - w id e and ser v es an est im at ed 2 00 m illion en d user s. The I MS/ D B dat ab ase ser ved t he Apollo pr ogr am in clud ing Apollo 1 1, w hich sent Ar m st r ong , Aldr in, an d pilot Mike Collin s t o t he m oon. Com pu t er Associat es' n et w or k dat abase pr odu ct is CA- I DMS, a w idely used d at abase ser v ing 2, 00 0 sit es ar oun d t h e w or ld . The p r oduct has chang ed in nam e and ow ner ship but cont inues t o su ppor t lar g e cor p orat e dat a sy st em s t hat r u n on I BM OS/ 390 p lat for m s. I DMS has an int er est ing hist or y . John J. Cullinane f ound ed Cullin et Soft war e, I nc. in 19 68. He bou ght t he r igh t s t o I D MS, a CODASYL dat abase, fr om B. F. Goodr ich. CODASYL, an acr ony m for Conf er ence on Dat a Syst em Langu ages, was est ablished in 1 960 by t he Depar t m ent of •Defense f or tTable of pose Content he pur ofs st and ard izin g lan guag es and sof t w ar e applicat ions. Cu llin et w as Pr ogr am m ing Or a cl e ® Tr i gger Storlist e ded P roce Thir dYor Edikti on t he fir st soft w ar e com panys and t o be ondure t h es,New St ock Ex ch ange. Comp ut er Associat es pu rchased Cullinet in Sept em ber of 198 9 an d renam ed t he p rod uct CA- I D MS. By Kevin Owens Alt hou gh CA- I DMS is based on dat ab ase net w ork archit ect ur e, t he p r oduct in clu des an ANSI comPub pliant ion.PTR This opt ion allow s applicat ions t o access I DMS dat a usin g SQL. A set lish er:SQL PrentOpt ice Hall of comp r eh siv ebert ools Pub Dat e: en Decem 0 5, 2 is 003av ailable t hat includes agent s for ent er pr ise m onit or ing, p ar allel t r ansact ion p rocessing u sing I BM Parallel Sy sp lex Clust er Techn ology , JDBC supp ort for Java, I SBN: 0- 13 -0 850 33 -0 and m any ot her eBu sin ess t echnolog ies. The maj or it y of I D MS ap plicat ion s ar e w rit t en in Pages: 44 8 COBOL. Or acle, pr ed omin at ely k now n f or t he Relat ional Ent er pr ise Ser v er, own s t w o ad dit ional dat ab ase pr oduct s: ( a) a net w ork dat abase pr od uct called DBMS, w hich is a COD ASYL Ef fect creat e an man age comab plex abases w it h Rdb. Or acle! st ems and dat ab dat ab ively ase, an d ( b) a dr elat ion al dat ase dat pr oduct called BotSy h Rdb and DBMS wase er e ex per t Kevin Ow ens ex plor esalPL/ SQL, Or tacle's answ er (tD o EC) t h e pr St ior r uctt ur Langu age ( SQL) pu rchased fr om Dig it Equ ipm en Corp orat ion o ted heQuery acquisit ion of DEC by , an d t eaches Com paq .you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using t oinst r uct ions ex am ples, book pr esent t echniq t ake , an Or acleeasyacq uir edfollow DBMS w hen it pu an r chdased t he Rdbt his pr oduct fam ily frs om D EC.ues Kent oOlsen advTant ag e ofe,Or acle feat esan, such asHar t riglan gers and st ored pr oced ur es-I n f eat r es t hat allow y our MI g r aduat h is br ot herurSt and And er son fou nded DEC. adudit ion t o har d war e datchab t o incor e bu siness r ules and w hich ar e o man andb, ma odif y ional as t he ar it ases ect u res such por as at t he PDP11 , VAX, Alph a,easy DEC tdev elopage ed Rd r elat bu sin cov edw include: dat abess ase,evolv an d es. alsoTopics DBMS, a er net ork dat abase. The net w ork d at abase w as r enam ed f rom VAX/ DBMS t o D EC DBMS wh en v ersion V5. 0 was released on t he Alph a AXP plat for m . View in g ASYL constD r aint s in e ult dati-auser dict ion y k dat abase t h at , lik e Rdb , is opt im ized f or t h e Or acle' s COD BMS is at hm netar w or Com paq Op en VMS op er at ing sy st em on eit her an Alpha or VAX ar chit ect ur e plat f orm . DBMS plex enf orcem ening t syst em s and shop floor sy st em s t h at r equir e st able is hig Com hly suit edr ule f or m anuf act ur env iron ment s w here dat abase inf or mat ion is f air ly st at ic. Con sillium Corp orat ion 's PL/ SQL p r ogr am un it s and langu age f eat u res Wor k St ream is t he m ost w idely inst alled Man ufact ur ing Execut ion Syst em ( MES) in t he sem icondu ct or and elect r onics indu st r ies. Wor kSt r eam has a long hist or y of r unn in g on Dat a t y pes and comp osit e st r u ct u re VAX/ DBMS and t oday ru ns pr im ar ily on VAX and Alpha ser ver s using Or acle COD ASYL D BMS. Er r or han dling and except ions Rd b7 w as Or acle' s fir st r elease of Rd b t h at w as con ceived and engin eer ed as an Or acle pr oduIct acle' s Rdb 7 is entions er pr ise relat ional dat abase op t imized for d igit al plat f or ms; nt.erOr- pr ocess com muan nicat t hat is, t he Hew let t - Packar d Cor por at ion' s OpenVMS oper at ing syst em and Com p aq D ig it al UNI X.Declar WhenatCom paq acq uirs,edincluding DEC it r ep laced ver sion of UNI X, called r ix,mwit iv e const r aint p rim ar y t khe eyDEC , u nique, f or eign k ey, ch eck ,Ult and uchh t he prmoduct or e nam e DI GI TAL UNI X—an oper at ing sy st em based on a 64- b it ar chit ect u r e t hat r uns on Alp ha AXP plat for m s. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce I n su mm ar y , dt he dat abase m ar ket clear inat eds by r elat t echan nology ; how for dat abase ev elopers, d esign er s,isand prlyojdom ect leader look in gion t o al b uild d m aint ain ev t r er uly, hier archical an d n et wor k d at abases con t inue t o m eet t he n eeds of en t er pr ise net w or k int ellig en t , com plex dat abases. com put ing env ir onm en t s. I BM I MS/ DB is a d omin ant hier ar chical dat ab ase t hat can ser v ice high - t r ansact [ Team LiB ] ion r at es and has a lar ge inst all b ase. Tw o net w or k dat abases—CA- I DMS, licensed by Com pu t er Associat es, and DBMS, licen sed by Oracle,—play crit ical r oles in supp ort of high - t r ansact ion ent er pr ise- w ide sy st em s. I n addit ion t o t he Or acle En t er pr ise Serv er , Or acle Cor por at ion also ow n s Rdb 7, a r elat ional dat abase, and D BMS, a n et wor k

dat ab ase—b [ Team LiB ] ot h pr oduct s ar e op t im ized for Comp aq plat for m s, including Alph a AXP. Tod ay t he Or acle D at abase Serv er add resses t h e needs of sm all and larg e bu sinesses t hat r equ ir e inf orm at ion pr ocessing for online t r ansact ion p r ocessin g ( OLTP) sy st em s, d ecision sup por t syst em s ( DSS) , plus t h e eBu sin ess solut ions. Th ese t y pes of ap plicat ion s can op er at e on sm all, st an d- alone ser ver s, or on dist rib ut ed, h ig h- av ailabilit y archit ect ur es.

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

1.2 SQL SQL m eans som et hing v er y specific, w her eas t he t er m dat ab ase h as br oad m ean ing and int erp r ever yd ay conv er sat ion. Th is sect ion elabor at es on t he SQL languag e as a st an dar d. Top ics in clu d im plem ent at ion , emb ed ded SQL, D ir ect SQL, and SQL* Plus as an im plem en t at ion of Direct SQL.

1.2.1 ANSI Standard SQL is a lan guag e cur rent ly defined in an ANSI st and ard ( t h e pr evious sect ion discussed t he hist fr om ofI BM t o ANSI ) . I f y ou are w r it ing an Or acle applicat ion t h at u ses SQL, t h en y ou •as it passed Table Content s SQL st at w®hose syn ax Stor comp w dure it h ANSI Pr ogr am mement ing Or ascl e Tr i gger s tand e dlies P roce s, Thir-dX3. Edi135 ti on - 199 9, " D at abase Lan guag e SQL. " By Kevin Owens

This ANSI st an dar d is available t o t he p ublic t h rou gh t he ANSI Web st or e. You can v isit t he sit e, ht t p: / / w ebst or e. ansi.or g/ an sidocst ore/ , w hich has a sear ch for m f ield. Using t he sear ch f ield, y o SQL st and ard s w it h a sear ch on " ANSI X3. 135 ." You can ob t ain copies of t h is docum en t in PDF f Pub lish er: Prent ice Hall PTR cost , as of t his w r it ing , is $1 8 an d it cont ains ab out 600 pag es. Pub Dat e: Decem ber 0 5, 2 003

I SBN: -0 850 The st an dar0d,13as wit33 h -0m ost st and ar ds, is defin ed using t he Back us Nau r Form sy nt ax—illust r at ed Pages: 8 , f r om ANSI - X3. 135 - 199 9, " D at abase Lan guag e SQL, " is sh ow n h er e t o illu st rat follow ing ext44r act pr eciseness w it h w hich t he st an dar d d ef ines t he sy nt ax of a CREATE TABLE st at em ent .

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

::= CREATE [ {t oGLOBAL ) LOCAL } an TEMPORARY ] TABLE
Using easyfollow inst r uct ions d ex am ples, t his book pr esent s t echniq ues t o t ake
adv ant agelement e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our [ COMMIT { DELETE ] e easy t o man age and m odif y as t he datON ab ases t o incor por at e I buPRESERVE siness r ules} wROWS hich ar
::= bu sin ess evolv es. Topics cov er ed include:
[ {
}... ] View in g const r::= aint s in t h e dat a dict ion ar y


Com plex r ule enf orcem en t |
PL/ SQL p r ogr am un it s and langu age f eat u res So, if y ou are a dat ab ase vend or and y ou sell a SQL d at abase pr od uct , t hen y ou ar e t elling you r y pes andprcomp st r u ct uof re p arsing and ex ecut in g ANSI SQL st at em ent s, such as t h t hat yDat ouradtat abase odu ctosit is ecapable afor em en t ioned CREATE TABLE st at em en t . Er r or han dling and except ions Ther e is alw ays an ad van t age t o w or king w it h a st and ar d. I t m eans t hat you r kn ow ledg e is t r ans I nt er - pr ocess com mu nicat ions An und er st and in g of SQL means t hat you r k now led ge of r elat ion al dat ab ase t echn ology can t ran bet w een pr od uct s such as Or acle an d SQL Ser v er . Even w it hin a st and ard t h er e ar e dif fer en ces. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch except ion. m or e SQL dif fer s across v endor s f or t w o r easons. Fir st , t h er e ar e " im plem en t at ion d ef ined" feat ur es in Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce st andar d ; t h at is, for som e SQL f eat ur es, t he specif ic nat u re of how a feat ur e is im plem en t ed is for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly " im plement at ion d ef ined" —t h e st andar d ex plicit ly st at es t his w it h t he lang uage " imp lem ent at ion int ellig en t , com plex dat abases. This m eans t h e v en dor h as discr et ion in how t he f eat ur e is im plem ent ed. One ex am ple is how t h im plem ent [ Team LiBs] t he cat alog or dat a dict ionar y. The st and ard cann ot im pose how a v endor st or es dat m et adat a. We' ll see lat er in t his chap t er how Oracle's d at a d ict ionar y is a set of r elat ional t ables w hich we can select t r em en dous amou nt s of inf or mat ion , such as infor m at ion descr ibing t h e t ab creat e.

A secondLiB reason w hy t her e ar e dif fer en ces acr oss dat abases is du e t o t h e fact t hat vend or s do en [ Team ] t heir specif ic SQL engin es w it h add it ion al capabilit ies t hat t hey f eel b en ef it t h e applicat ion develo exam ple is t he DECODE SQL f unct ion t hat y ou w ill f ind in Oracle. This is a pow erf ul fun ct ion t h at necessar ily ap pear in ot her dat ab ase pr oduct s sim ply because DECODE is not par t of t he ANSI s Anot h er ex am ple is t h e dat ab ase colum n t y pe CURRENCY t hat you f in d in SQL Ser ver —not all da pr odu ct s pr ov id e a CURRENCY t y pe. These diff erences ar e m in or com par ed t o t he m any con sist e across SQL p r oduct s t h at ar e ensur ed b y t he ANSI st an dar d. I n su mm ar y , y ou w ill f ind var iat ions in som e SQL st at em ent s acr oss dat ab ase en gines—t his is r e big deal. For exam ple, if y ou build you r exp er t ise in SQL and you bu ild t h is kn ow ledg e in Or acle, k now led ge w ill include an u nder st anding of inn er and out er j oin s. I f y ou ar e ever conf ron t ed w it h syn t ax of out er j oins f rom a SQL Ser ver or D B2 ap plicat ion , w her e t his sy nt ax v ar ies, t h en y ou c m ake t he k now ledge t ran sit ion. The k ey issue is t o r ecog nize t hat t her e ar e dif fer en ces, because likely t o becom e ex posed t o t hese diff erences at som e p oin t in y our car eer . Wh en t his h appens, r em em ber t hat pr odu ct s w ill hav e subt le d if fer ences ev en u nder t h e um br ella of an ANSI st an da •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

1.2.2 SQL Database By Kevin Owens

The t er m dat ab ase is used of t en in ev er yd ay langu age, but it is im por t an t t o r em em ber t hat not " datPub abases" areice cr Hall eat ed lish er: Prent PTR equ al. Nor can t h ey all be called r elat ion al dat ab ases. The t er m r elat ion dat ab r efer s t ber o one on t he SQL st and ard t h at is capab le of par sing an d ex ecut in g SQL Pubase Dat e: Decem 0 5, 2based 003 st at ement s. We can b e v er y gener al in how we use t he t er m d at abase, but t he t er m r elat ional d I SBN: 0- 13 -0 850 33 -0 does conv ey a d at abase t hat is based on t h e SQL st andar d—som et hing v ery sp ecific. Pages: 44 8

I n con t rast t o r elat ional d at abases, t here ar e n onr elat ion al dat ab ases, such as DBMS. D BMS is a pr odu ct licensed by Or acle and is not a r elat ional d at abase—it is a net w ork d at abase. Access t o t hr ou gh a lang uage sim ilar t o SQL, bu t it is not SQL per ANSI st and ard . Som e dat ab ases, such a Ef ively creat e an man agey et com plexprdat abases w it hend Or acle! Sy st ems dat ab per t t h ar fect e not r elat ional datdabases, t hey ov ide a fr ont t hat allow s an and ap plicat ionase t o ex access Kevin Ow ens ex plor PL/ fr SQL, answyerdoes t o t hnot e Stmr ake uct urI DMS ed Query Langu SQL) , an using SQL. Havin g aesSQL ont - Or en acle's d cap abilit a relat ionalage d at(abase. A rdelat tdat eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ab ase is relat ional wh en it con for m s t o t he m inim um r equir em en t s of t he ANSI SQL st an dar d Using o- follow uct ions anab d ase. ex am ples, t his dat book pr esent s t echniq t ake Or acleeasyis a ftully SQL- inst comrpliant dat An Or acle ab ase con sist s of m ues any tfoiles t hat ar e p re adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat allow y our dist r ibut ed across sever al disk par t it ions—d ist r ibu t in g files min im izes I O con t en t ion. dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

1.2.3 SQL Implementation View in g const r aint s in t h e dat a dict ion ar y Giv en t h at Oracle is a relat ional d at abase and w e access Or acle dat a using SQL, how d oes one c Com r ule enld t w r it e a Visual Basic, C, Per l, or Java pr ogr am . You cou ld w r it e j m anipu lat plex e t hat datenf a? orcem You cou any p r ogr am in any lang uage y ou w ant and em b ed SQL st at ement s in y our pr ogr am . These st at PL/ SQL am unitit, sand anddelet langu age f eatapplicat u res ion p rog r ams can pot ent ially ex ecut e any v w ill inser t datpa,r ogr ch ange e it . Our st at ement again st our r elat ional d at abase. Dat a t y pes and comp osit e st r u ct u re SQL, or ig inally called SEQUEL, desig ned b y I BM, and b ased on Codd' s r elat ion al t heor y , pr ov id ed Er r or han dling and except ions access m et hods f or t h e Syst em / R pr oject . The p r im ar y pu rp ose of SQL t oday is t h at w e u se it in similar t o w hich it w as used b y Sy st em / R; t hat is, t o b e em b ed ded w it h in a pr ogr am min g lan gua I nt er - pr ocess com mu nicat ions pr ov ide dat a access m et hods ag ainst d at abase t ables f or a p rod uct ion sy st em . One cor e diff eren day - t od ay at cod per sp ects, iv e, bet w eenp rim pr ogr s of oday an t hose of Syst em / R ismt hat Declar iv ing e const r aint including ar yam k ey , utnique, f ord eign k ey, ch eck , and uch w e ar likely m t ooruse a m or e cur r en t p rog ram m ing langu age, such as Jav a or C# . Second ly, p r ogr ams w e e t oday ut ilize en hancem en t s t o t he SQL st and ard s—t his includes t h e k ey com pon en t s of t his t ex t : Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Dat ab ase con st r aint s int ellig en t , com plex dat abases. Tr igger s [ Team LiB ] St or ed p rocedur es Sup pose you j ust w an t t o do som et hing sim ple and qu ick . Let ' s say y ou w an t t o creat e a t able w

colum an d] in ser t one r ow int o t hat t able. For such a simp le t ask, t he eff or t t o code and com pile [ Teamn LiB pr ogr am seems ex cessive—and it is. For a sim p le SQL in t erf ace w e use t ools t hat add ress t h e " d inv ocat ion of SQL. " Th e SQL st andar d addr esses em bedded SQL—an d t his is w hat has b een disc t o t his poin t , emb ed ding SQL st at em en t s w it hin com piler lang uage p rog r ams—bu t t he SQL st and add resses an ot her m et hod r ef er r ed t o as Dir ect SQL. This is w her e w e do t he sim ple an d q uick s The SQL St andar d specif ies t h ree ap pr oach es t o SQL: em bedded SQL, m odular SQL, and D ir ect Em bedd ed an d m odu lar SQL ar e pr incipal t echniq ues for applicat ions dev elop ment using a com p langu age—t hey ar e gr eat f or ap plicat ion s developm ent but im pr act ical f or simp le t asks an d for l t he SQL lan guag e. I f w e did not hav e an im p lem ent at ion of Dir ect SQL and w ant ed t o see all t he r ow s of a t able, w hav e t o w rit e an ap plicat ion pr og ram , em bed a SQL cur sor, fet ch each row int o local v ar iables a t hose v ar iables out t o som e defau lt dev ice. A t ool t h at im plement s Dir ect SQL allow s u s t o disp la sam e dat a in ab out 5 secon ds—m ost ly lim it ed t o how fast we can t y pe or dr ag- and - dr op. Rat her com piled pr ogr am , Dir ect SQL allow s us t o t y pe a SQL SELECT st at em ent wh er eby all row s ar e f •our scr een for Table of ing. Content s view Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

The ANSI st an dar d descr ipt ion of dir ect SQL is st at ed in t he f ollowin g: By Kevin Owens Dir ect inv ocat ion of SQL is a mechan ism f or execut ing d ir ect SQL- st at em ent s, k now n as < d inv ocat ion of SQL, t he met h od of inv ok ing < dir ect SQL st at em ent > s m et hod of raising condit ions t hat result fr om t h e ex ecu t ion of < d irect SQL st at em en t > s, t h Pub Dat e: Decem ber 0 5, 2 003 of accessin g t he diag nost ics in for m at ion t hat r esult s f rom t he ex ecut ion of < dir ect SQL st at I SBN: 0- 13 -0 850 33 -0 and t h e m et h od of r et ur nin g t h e r esult s are im plem en t at ion- d ef ined.

stlish ater: ement I n PTR dir ect Pub Prent> ices.Hall

Pages: 44 8

Not ice t hat Dir ect SQL is " imp lem ent at ion defin ed ," hence v endor s hav e w ide d iscr et ion in how t im plem ent Dir ect SQL. SQL* Plu s® is an Oracle im plement at ion of Dir ect SQL, as is SQL Ser ver 's Analy zer. These t ools diff er in u ser int er face; h ow ev er, t he sam e SQL qu er y st at em en t , execut ed Ef fect ively creatweillanprd odu man dat abases w it is, h Or acle! ems andnu dat per dif fer en t t ools, ceage t hecom samplex e r esult set ; t hat t he samSy e st dat a and mab berase of ex row s twill Kevin sam e. Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Ther e exist s a w id e v ariet y of SQL t ools t h at im plem en t dir ect SQL. These t ools allow us t o t y pe Using easyo- follow inst d ex amad ples, t his com bookplexit pr esent uesort oscr t ake st at ement s tand execut e trhuct emions w it han out t he dit ional y ofs at echniq com piler ipt ing lang ua adv e ofsom Or acle as t rig gersline andint ster ored pr Ex oced es- fof eatsu u ch r est ools t hat ar allow y ourPlus ar e ant GUIagand e pr feat ov idur e es a bsuch asic com m and face. amur ples e SQL* ® , wage datndled ab ases por at edat buabase siness soft r ules we; hich ar eNav easy m odif y as he est Sof t w ar bu witt oh incor t h e Or acle war SQL igatt oorman hichand is licensed b y tQu bu sin ess evolv es. is Topics cov er Wor k sh eet wh ich bu ndled w itedh tinclude: he Or acle Ent er pr ise Manag er ( OEM) soft w ar e; and TOAD , w h a Quest Soft war e p rod uct . Th er e ar e m any ot h er t ools as w ell. g constural aint in en t hce e dat dict ion ar y Ther eView is a in concept difsfer b etaween accessing Or acle, or any r elat ional d at abase, t hr ough a langu age such as Jav a an d u sin g a dir ect quer y t ool lik e TOAD or SQL* Plus. All t ools t hat im plem Comat plex r ule eniv t e fr am ew ork so you need t o k eep t he follow ing t w o poin t s in min SQL oper e w it hin enf an orcem int eract w hen you ex ecut e a qu er y w it h SQL* Plus, or w it h any d ir ect SQL t ool, t he r esu lt s are dum ped t o PL/ SQL p r ogr am un it s and langu age f eat u res scr een. Secondly , w hen ex ecu t ing t he sam e qu er y w it hin an app licat ion, you m ust d ev elop code t he result s of y our q uer y. Th is is illu st rat ed w it h t he f ollow ing t w o SQL quer y st at ement s. Dat a t y pes and comp osit e st r u ct u re The f ir st SQL st at ement is a q uer y t hat you w ould execut e in SQL* Plus. Upon execut ion of t he st Er r or han dling and except ions t he st u dent nam e is flu sh ed t o t he scr een. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e 1. SELECT student_name student_id = 'A101'; Pr ogr am m ing Oracle Tr iggerFROM s and registered_students St or ed Pr oced ur es , Th ir WHERE d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. The af or em ent ioned SELECT st at em ent is a v alid SQL st at em ent f or Dir ect SQL only . I t will n ot c an em b ed [ Team LiBded ] SQL st at em ent w it h in a com p iled pr ogr am . The SELECT st at em en t em bedded in a app licat ion pr ogr am w ill be sligh t ly diff erent —t he dif fer en ce is t he ad dit ional I NTO clau se, show n I NTO clause w ill r ef erence a pr ogr am v ar iab le int o wh ich t h e st udent nam e is t o be copied.

[ Team LiB ] [View full width] 2. SELECT student_name INTO my_program_variable FROM registered_students WHERE s = 'A101';

Ther e ar e v ariat ions on t he afor em en t ioned q uer y t hat use t he I NTO clause—w e h ave ex plicit cu cur sor loops, and ot her op t ions—t hese t opics ar e cover ed in Ch apt er 11 . I t is helpfu l t o keep in m SQL* Plus, like Toad an d ot her dir ect SQL t ools, is pr im arily an int er act iv e t ool—y ou do not w or r y capt ur ing r esu lt dat a. On t he ot her hand , app licat ion pr ogr am s do capt ur e q uery r esult d at a an d dev elop code t o " capt ur e d at a" y ou hav e desig n issues: m ult iple r ow s r et ur ned ex cep t ion con dit t opics ar e add r essed t h rou ghou t t h e t ext .

1.2.4 SQL*Plus • Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

IBynKevin additOwens ion t o b ein g an im plement at ion of D ir ect SQL, SQL* Plus is a t r ademar k ed n ame for an O execut ab le pr ogr am t hat r uns as a com m and lin e int er act iv e pr og ram . As ment ion ed in Sect ion t her e ar e m any SQL t ools on e can u se t o ex ecut e SQL against a dat ab ase. We' ve ment ion ed SQL Toad, SQL or, PTR and SQL Wor ksheet . I n fact , y ou can u se SQL Ser v er SQL Quer y Analyz er Pub lish er: Navigat Prent ice Hall qu erPub iesDat against you r Or acle dat abase. You hav e m any choices. This t ext m akes u se of SQL* Plu s, e: Decem ber 0 5, 2 003 hav e no dif ficult y f ollow ing along should y ou use anot her t ool for in t eract ing w it h Or acle. I SBN: 0- 13 -0 850 33 -0

Pages: 44 8 ar ily ser ves an end user in a client / ser ver env ir onm en t . Figur e 1- 1 illust r at es a co SQL* Plus p rim conf ig ur at ion t hat in clu des SQL* Plus. I n t his fig ur e, t he com mu nicat ion p r ot ocol acr oss t h is net w Or acle Net 8 p rot ocol. Th e Or acle sof t w are t hat ru ns on y our clien t sends t he SQL st at em en t acr o net w or k t o t he dat abase and it is Oracle soft w ar e, on t he b ack en d, t h at f orw ar ds t he d at a back client I f you r une SQL* Plusage andcom t y peplex t hedat f ollow ing SQL em enSy t : st ems and dat ab ase ex per t Ef fect.ively creat an d man abases w it h st Oratacle! Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SELECT student_name registered_students student_id = 'A101'; dat ab ases t o incor por at eFROM bu siness r ules w hich ar e easyWHERE t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

Figu r e 1 - 1 . SQL* Plus in a Cl ie nt / Se r ve r M ode .

View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t

PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions t he SQL st at em ent , ex act ly as y ou t y pe it , including t h e same case, is sen t acr oss in a net w or k p t he OrDeclar acle serv . The rpaint rocessed r esult ,p trim hatarbein g ,a ulist of stfudent in t ,his case pr obab ly at iver e const s, including y k ey nique, or eignnam k ey,esch( eck and m uch one nm am oree of t he st ud en t w it h t hat par t icular st ud en t I D) , is ret u rn ed t o t he SQL* Plus client wh e flu sh ed t o you r scr een. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Thedat send in g an d elopers, receiv ingd esign of dater a s, is and Or acle , w hichs look is Oracle m unicat for abase d ev pr ojNet ect8 leader in g t ocom b uild an d mion aintsof aint wt are r uly and r TCP/ I P,enort , ot herplex net w orabases. k pr ot ocols. SQL* Plu s is w r it t en t o ut ilize Net 8, w hich ut ilizes TCP/ I P ov e int ellig com dat net w or k. [ Team LiB ] SELECT, I NSERT, UPDATE, an d DELETE are t he m ost com m on SQL st at em ent s—t hey ar e t he cor m anipu lat in g dat a. I n addit ion t o t hese cor e d at a m anipu lat ion st at em ent s, t he SQL st an dar d in specif icat ion f or st at em ent s lik e: CREATE DATABASE, ALTER DATABASE, CREATE TABLE, CREAT

CREATE TRI]GGER, and m any ot her SQL comm and s. Any v alid SQL st at em ent can be ex ecu t ed f r [ Team LiB SQL* Plus, includin g t h e ALTER D ATABASE st at em en t . So, all SQL st at em ent s, not ju st t h e com m I NSERT, UPDATE, DELETE, SELECT can be ex ecu t ed f rom SQL* Plu s. Ther e ar e m any adv ant ages t o lear ning SQL* Plus. A f ew ar e sum mar ized here. You w ill find SQL* Plus in t he Or acle b in d ir ect ory of ev ery Or acle inst all. I f y ou in st all t he d an en t erp rise serv er, you w ill f in d SQL* Plu s in t he bin dir ect or y . I f y ou inst all j ust t he Or ac dev elop er sof t w are on t h e deskt op , y ou also hav e SQL* Plu s. This ex ecut ab le pr ogr am is alw So, in t he ab sen ce of h avin g an y ot her t ools, y ou can alw ay s be sur e y ou hav e t he SQL* Plu pr ogr am . Becau se SQL* Plu s has b een available f r om Or acle t hr oug h so man y v er sions, t he p r ogr am ext r em ely w ide user base. I t is pop ular for sev er al reasons, one of w h ich is t h e fact t hat it ar ound f or so m any y ear s. •

Table of Content s

SQL* Plus ise ® a Tr sim ples com m and ers,face prEdi ogtiram Pr ogr am m ing Or a cl i gger and Stor e d Pline roceint dure Thir d on .

I t ' s not a GUI in t er f ace; you do not m ult iple scrollable w ind ow s t hat show t h e SQL st at ement in one w indow and t he quer y r es By Kevin Owens anot h er w in dow . Alt hou gh GUI feat u res h ave t h eir adv ant ages, t he sim plicit y of SQL* Plu s b adv ant ag eou s w hen you need t o b uild scr ip t s. You can bu ild a lib rar y of SQL* Plus scr ipt s, e ASCI t ex t ice f ile, d t hose scr ipt s will r un on Or acle in UNI X or on Or acle in Window s. Pub lish er:I Prent Hallan PTR Pub Dat e: Decem ber 0 5, 2 003

SQL* Plus h as all t he feat ur es of a p ower fu l scr ipt in g lan guag e. I t supp ort s arg um en t p assin I SBN: 0- 13 -0 850 33 -0 com man d f iles, an d n est ed com m and f iles. You can h ost out t o ot her langu ages ( e.g . , em b Pages:ows 44 8 scr ipt host f ile or Kor n shell scrip t w it hin a SQL* Plu s scr ipt ) . SQL* Plu s scr ipt s can Wind incor por at ed int o ot h er scr ip t ing pr ogr am s ( i. e. , SQL* Plu s scr ipt s can be em bedd ed in Korn scr ipt s; illu st r at ed in Ch apt er 2) . Th ese f eat ur es m ak e t h e langu age high ly useful for t ool b

n su mm arey ,an alt ghage SQL* Plu s isdat an abases ex cellent o fir stSyex and Ef fectIively creat d hou man com plex w itthool Ortacle! stperience ems and SQL dat ab aseOr exacle, per t it is idely ases a dev elopmOr ent and answ adm inist Peop le w hoLangu u se SQL* s init ially KevinwOw ensused ex plor PL/ SQL, acle's er t or at t hion e Stt rool. uct ur ed Query age Plu ( SQL) , an d u int ryou odu ce t hemselves yearrob s lat t hey 'r e plex st ill using f or fapp develop t eaches w hat y ou n eed t o t o Or knacle, ow t ob ut build usteran d com dat ab it ases or ylicat our ions b usiness. dat ab ase adm inist rat ion . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake [adv Team LiB ] Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our ant ag e of dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

1.3 Tables Dat ab ase t ables are t he m ost f und am en t al st r uct ur e in a dat abase. I f y ou w er e ask ed t o w ork on a n ew Or acle d at abase, you w ould init ially w onder h ow m any t ab les t here are in t h e app licat ion. I t m akes a diff erence w het h er t here are six t ab les or 600 t ables, at least in t er ms of how mu ch t h er e is f or y ou t o learn ab out t he app licat ion befor e y ou can b e a p rod uct ive dev elop er . The ex am ples in t h is t ext ar e based on a demo st udent dat a m odel. The m odel st or es dat a for st udent s, cou rses, and pr ofessors. Ch apt er 4 g r aphically illust r at es t his mod el in clu ding t he SQL cr eat e scr ipt s. A k ey t able in t his m od el is t he STUDENTS t able. •

Table of Content s

Pr ogr amial m ing Or afor cl e ®a Tr i gger s and Stor e d Pr equir roce dure Thir derEdi ti on An init plan STUDENTS t able es s,answ ing t he quest ion: " What at t r ib ut es should be st or ed for each st u dent ?" An in it ial dr aft of a STUDENTS t able includ es t hese By Kevin Owens at t r ibut es:

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

At t r ib ut e

Colum n N a m e

I SBN: 13 -0 850 33 -0b er . Each st ud en t is assigned a nu m ber used t o A u niqu e st0udent num Pages: 44 8 and r eg ist r at ion r ecor ds. access billing

STUDENT_I D

A st u dent nam e.

STUDENT_NAME

A m aj or field of st u dy such as Science or Hist or y . COLLEGE_MAJOR Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t A college enrex ollm ent at us indOr icat in g aansw degrer ee-t oseeking t ificat e- Langu STATUS Kevin Ow ens plor es stPL/ SQL, acle's t h e St ror uctcer ur ed Query age ( SQL) , an d seek ing st udent . t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easyions an ds. ex ples, t his s t echniq t ake Tables hav et od iffollow fer en t inst r eprr uct esent at ion Oram iginally, t he book t ab le pr isesent a logical ent it yues cont osist ing of a adv ant of Or ur es diagr such am as .t rig andion, st ored ocedcan ur esu r es t hat box on ag ane ent it y acle r elatfeat ionship I n gers p r oduct t he pr t able bef eat d escr ibed w itallow h t hey our dat abPlus asesDescrib t o incorepor atm e and bu siness ules w hich e easy SQL* com and rrow s can be ar select ed. t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

1.3.1View Data Model in g const r aintView s in t h e dat a

dict ion ar y

plex enfoforcem en t ident if ies t h e logical at t r ibut es of t h e ent it y b eing st or ed in The dCom at a m od elr ule view a t able t he dat abase ( Figur e 1- 2 ) . Th is inclu des a k ey at t r ibut e, wh ich is t h e pr imar y k ey. The PL/ SQL p ruogr am fun s andinlangu age resit y . I f t he t able st or es st u dent s, ever y pr im ary key is nique or iteach st an ce of fteat he uent st udent w ill hav e a uniqu e pr im ary key . The d at a m odel v iew is a g r aphical r ep r esent at ion. Dat a t y pes and comp osit e st r u ct u re

Figu e 1 - 2ions . St ude nt s Er r or han dling andr except

Tabl e in a D at a M od el .

I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

1.3.2 ICreate SBN: 0- 13 -0 Table 850 33 -0 Script Pages: 44 8

On ce t he m odel is com plet e and all at t r ibu t es are defined, t he ent it y m ust be cr eat ed in t he dat ab ase. SQL is used t o cr eat e a t able. This st ep t ran sit ion s t he logical concept t o a phy sical t able in t h e dat abase. Wh en SQL cr eat es ob ject s, su ch as t ab les, t h is is called Dat a Def init ion Lan guag e (creat DDL)e. an The in gcom DDLplex creat esabases a STUDENTS able Sy anst d ems defines e colu mnex t yper pe t Ef fect ively d follow man age dat w it h Or tacle! andt hdat ab ase of eachOw atens t r ibuex t eplor t o es be PL/ a vSQL, ar iable st r ing um Kevin Or lengt acle'sh answ er wt oit ht hae m Staxim r uct ur edsize. Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he CREATE TABLE students bu sin ess evolv es. Topics cov er ed include: (student_id VARCHAR2(10), student_name VARCHAR2(30), college_major View in g const rVARCHAR2(15), aint s in t h e dat a dict ion ar y status VARCHAR2(15)); Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res

1.3.3 Describing the Table

Dat a t y pes and comp osit e st r u ct u re The d ef init ion of a t ab le can easily b e descr ibed w it h t h e SQL* Plus com man d. Th is com m and Eres r orinhan except r et riev for mdling at ionand f r om t he dions at a d ict ion ary in a for m at t h at conv eys t he inf or mat ion st or ed in t he t ab le. I f t h e DDL in t he p rev ious sect ion w ere used t o cr eat e t h e STUDENTS t ab le, t he I nt erd- pr ocess comm mu nicat ions r et ur n t he f ollow ing : SQL* Plus escrib e com and w ould Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for datdesc abasestudents d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly SQL> int ellig en t , com plex dat abases. Name Null? Type -----------------------------[ Team LiB ] STUDENT_ID STUDENT_NAME COLLEGE_MAJOR STATUS

-------NOT NULL NOT NULL NOT NULL NOT NULL

--------------VARCHAR2(10) VARCHAR2(30) VARCHAR2(15) VARCHAR2(15)

[ Team LiB ]

1.3.4 Table Data SQL st at ement s t hat m anipulat e row s in t he t able ar e called Dat a Manipu lat ion Langu age ( DML) . On ce t he t ab le is cr eat ed, w e can add st udent s t o t he syst em w it h I NSERT st at ement s.

INSERT INTO students VALUES('A101','John','Biology','Degree'); •

Table of Content s

A ogr k eyamcomp echn emp Pr m ing onent Or a cl e ®ofTrrelat i ggerional s and tStor e dology P roce ,dure s, hasized Thir d Edi tiin onSect ion 1. 1 , is t h e fr eedom of t h e pr ogr am m er t o choose w hat dat a t o quer y. Once t he t able is cr eat ed and r ow s ar e inser t ed, By Kevin Owens t her e is no r est r ict ion w it h dat a access. We can q uer y all st udent s w it h in a par t icular m ajor . We can quer y all st ud en t s w ho are degr ee can didat es. We can quer y all degr ee- seeking st udent s m ajor ing in eit her b iolog y or hist or y. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

SELECT student_name FROM students WHERE college_major = 'Biology'; SELECT student_name FROM WHERE status = acle! 'Degree'; Ef fect ively creat e an d man agestudents com plex dat abases w it h Or Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d SELECT student_name FROM WHERE t eaches you w hat y ou n eed t o students kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. status = 'Degree' AND (college_major='Biology' OR college_major='History'); Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Idat n net w ork t an d hier ar at chical dat ab ase t echn ologies, t h e pr am m erand canmnot , at t het he last ab ases o incor por e bu siness r ules w hich ar e easy t o ogr man age odif y as m e, devolv ecidees. t o Topics qu er y dcov at aerineda include: p art icular or d er . I n net w or k and hierar chical dat abases, buinut sin ess or der ed qu er y r esu lt s m ust b e built int o t he dat abase st ru ct u r e. I n r elat ion al dat ab ases w e can, as developers, ch oose t o select st ud en t s and t h eir m aj or in alp habet ical or der , r ev erse View in gorconst aint h e dat dictor ion ar yby m aj or—we hav e no rest r ict ion. The or der ing alphab et ical d er , ror ders in b y t nam e, aand der of dat a is not in t he dat abase but w it hin t he SQL st at em ent . So t o p ull all st ud en t n ames an d Com plex r ulehabet enf orcem t w e use t he ORDER BY clau se, w h ich is a com pon en t of t h e t heir m ajor in alp ical oren der, SQL specif icat ion . Show ing t his ord er ed list , w e u se: PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SELECT student_name, major FROM student ORDER BY student_name; I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch All r ow msorof e a t able can b e select ed w it h t he SELECT * syn t ax. The f ollow ing is t h e SQL* Plu s session ou t pu t t h at select s all r ow s f rom t his STUDENTS t able af t er fiv e st udent s hav e been add edam . m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Pr ogr for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] SQL> SELECT * FROM students; STUDENT_ID STUDENT_NAME

COLLEGE_MAJOR STATUS

---------[ Team LiB ] A101 A102 A103 A104 A105

--------------John Mary Kathryn Steven William

-------------Biology Math/Science History Biology English

----------Degree Degree Degree Degree Degree

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

1.4 SQL Statements The SQL lan guag e is pr im arily used t o cr eat e t ables and m anipu lat e t able dat a; how ev er , t he langu age includ es st at em ent s t h at p er f orm ot her fu nct ions. SQL st at em en t s ar e used t o creat e d at abase account s, size and t u ne f or per for m ance, and perf or m adm inist r at ion t ask s. An Or acle d at abase f ir st com es int o ex ist en ce wit h a SQL st at em ent , t he CREATE DATABASE st at ement . The f ollow in g d escr ib es t he cat egor ies of SQL st at em ent s.

1.4.1 Data Definition Language (DDL) •

Table of Content s

CREATE ise ®a Tr DD L stsat emStor ente.dDPDL at em entds Edi d eftiine Pr ogr am mTABLE ing Or a cl i gger and rocest dure s, Thir on ou r dat ab ase ob ject s and r esu lt in up dat es t o t he Or acle dat a dict ionar y. They creat e, m odif y, an d delet e ob ject s such as a By Kevin Owens t ables, v iew s, st or ed pr ocedur es, dat abase t r igg er s, dat abase lin ks, an d dozens of ot h er obj ect s in t h e dat ab ase. Pub lish er: Prent ice Hall PTR

DDL st at em en t s can alt er ex ist in g d at abase obj ect s in clu ding t ables. Colum ns and const rain t s Pub Dat e: Decem ber 0 5, 2 003 can be add ed w it h t he ALTER TABLE comm and . Shou ld w e choose t o add a colum n for a 33 -0 st udentI SBN: 's ag0-e13 w-0 e 850 can ex ecut e t he f ollow in g SQL st at em en t , w hich alt er s t h e defin it ion of t h e Pages: 8 abase d at a d ict ionar y . t able in t h e 44 dat

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER students ADD t eachesTABLE you w hat y ou n eed t o (age kn ow NUMBER(3)); t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 1.4.2 Data Manipulation Language (DML) dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: DML m anip ulat es dat a w it h t h e follow ing st at ement s: View in g const r aint s in t h e dat a dict ion ar y I NSERT Com plex r ule enf orcem en t UPDATE PL/ SQL p r ogr am un it s and langu age f eat u res DELETE Dat a t y pes and comp osit e st r u ct u re SELECT Er r or han dling and except ions SELECT st at em ent s d o n ot act ually m anipu lat e dat a, but t he SELECT st at em en t is of t en included t he com convmu ersat ional I nt erw-itprhin ocess nicat ionscon t ext of " DML." An OrDeclar acle d at abase pr ov ides able chanpges hryoug an dchDELETE iv e const r aint s, tincluding rim tar k eyh, IuNSERT, nique, fUPDATE, or eign k ey, eck , andt om uch cohabit m at or e wit h SELECT st at ement s. The concep t sup por t ed in an Or acle en vir onm ent is called consist ent r ead im age. A user m ak ing un com m it t ed chan ges t o t he d at abase t hr oug h IPrNSERT, andTrDELETE st atSt em not au ser w h, oisissu SELECT dur ing ogr am mUPDATE, ing Oracle igger s and oren edt sPrdoes oced ur esblock , Th ir d Ed it ion an es invaaluable r esou rce t hatdat sam e t ime am e. Tran sact ions su ch pr asojan NSERTs tlook hat in arge tnot comm t o tain h e t r uly for abase d evfrelopers, d esign er s, and ect I leader o b uild anitdt ed m aint datellig ab ase n otplex in t erdat f erabases. e w it h concur rent SELECT st at em ent s ag ainst t h e same t ables. A int en t do , com SELECT st at em ent is guar an t eed a consist en t im age. Th e result s r et ur ned t o t he user fr om a [ Team LiB SELECT st at]em ent ar e guar ant eed t o b e fr om t h e m ost r ecent con sist ent imag e, w hich w ill be t he row s as of t he m ost r ecent COMMI T. A COMMI T st at em ent est ab lishes a new check poin t by w h ich t able d at a is u pdat ed t o a consist en t poin t in t im e.

[ Team LiB ]

1.4.3 Transaction Control Tr ansact ion cont r ol st at em ent s allow y ou t o b und le a gr ou p of D ML st at em ent s u nder an allor - not h in g dom ain. That is, " all st at em en t s comp let e su ccessf ully, " or if one st at em en t f ails, t hen all st at em en t s fail as one gr ou p. Ex am ples of t r ansact ion cont rol st at em ent s ar e: SET TRANSACTI ON, COMMI T, and ROLLBACK.

1.4.4 Session Control Session Cont r ol st at em ent s ar e t em por ar y and per sist for t h e du rat ion of t he user ' s dat ab ase connect ion. A usef ul SQL t unin g p ract ice is t o t ur n SQL t r ace on f or t he session . This r ecor ds session in for m at ion t o a user d um p dir ect or y f or SQL st at em ent analy sis u sin g t he Or acle t ool, TKPROF. The f ollow ing w ill t ur n t r acin g on/ off f or t h e session . •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

ALTER SESSION SQLTRACE [TRUE|FALSE] Pub lish er: Prent iceSET Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

On ce SQL Tr ace is on, t he u ser r un s t he applicat ion. Du rin g ex ecut ion Or acle w r it es d at a t o a Pages: 44 8 t r ace file. The t r ace f ile can be an alyzed using t he Oracle ut ilit y , TKPROF. The f ollow ing show s t he host com m and st ring t o par se t he t race f ile. Th e r esult aft er r un ning TKPROF is an ou t put ASCI I f ile sh owin g each SQL st at em ent ru n wit h d et ail t uning inf or mat ion . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easyt o- follow inst r uct ions anoracle_output_trace_file.prf d ex am ples, t his book pr esent s t echniq ues t o t ake tkprof oracle_trace_file.trc adv ant ag e of Or acle feat ur es sys=no such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our explain=SCOTT/TIGER@ORA dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: The f ollow in g is a com mon alt er session com m and. I t alt ers t he d ef ault disp lay for m at f or colum ns w it h a D ATE t y pe t o includ e: day , m ont h , y ear , h our s, m in ut es, and second s. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res ALTER SESSION SET NLS_DATE_FORMAT='dd-mon-yyyy hh24:mi:ss'; Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions

1.4.5 System Control

I nt er - pr ocess com mu nicat ions

Sy st em Contatr ol at emren t s s,arincluding e lar gely p dat abase r at iv e eign com m andch s. eck The, and SQL m uch Declar iv estconst aint rim ar y k adm ey , uinist nique, f or k ey, st at ement s ar e used t o open t he d at abase, sh ut dow n t he d at abase, and per for m m or e adm inist r at ive com m ands su ch as r esize dat af iles or sw it ch log f iles. The f ollowin g is a syst em r olOracle st at emTrent u sed t o St setorted he Pr n um ber acle Pr ogr amcont m ing igger s and oced ur of es Or , Th ir d job Ed itqueue ion , is pr anocesses. inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] ALTER SYSTEM SET job_queue_processes=4 SCOPE=BOTH;

[[ Team Team LiB LiB ]]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

1.5 Table Column Datatypes The m ost com m on dat at y pes ar e VARCHAR2, NUMBER, and DATE. These t yp es hand le basic colum n t yp es f or char act er st rin gs, num b er s, and colum ns w it h a t im e d imension. The exam ples in t his t ex t , includ in g t he dat a m odel in Ch apt er 4, u se t hese t hr ee t yp es. Oracle pr ov ides m any ot h er d at at y pes w it h pow er f ul f eat ur es. Som e dat at y pes ar e sup plem ent ed w it h built - in fun ct ion s and pack ages. Built - in fun ct ion s ar e av ailab le t o conv ert a DATE bet w een t ime zones. Lar ge ob ject s, su ch as CLOB and BLOB t y pes, ar e su ppor t ed w it h a PL/ SQL b uilt - in packag e, DBMS_LOB w hich en ables t he m anipu lat ion of 4- gigaby t e ob ject s. The f ollow ing list s t he d at at y pes av ailab le for colum n •defin it ion s inTable ofle. Content s a t ab Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

1.5.1 Character Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

VARCHAR2(n) Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tThe eaches you w hat ou general n eed t o st knr ing ow tt oy pe build robt oust anedstcom plex y our VARCHAR2 is yt he u sed st or r ings of dat up ab t o ases 4 ,0 00f orchar actberusiness. s. A field of t his t y pe is, int er nally , a v ar iable len gt h st r in g. I t only uses t he min im u m necessary Using easy-p taddin o- follow instpar r uctam ions annd isexrequ am ples, his book pr esent s t echniq ues t o t ake ir ed. tFor t he colum n STUDENT_NAME, in t h e by t es—no g. The et er adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our STUDENTS t able, w e can st or e a nam e up t o 30 ch aract er s. dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess Topics cov verersions ed include: Or acle verevolv sion es. 6 and ear lier u sed a VARCHAR t hat was a f ix ed leng t h ch aract er f ield. Or acle int r oduced t his v ar iab le len gt h and m ore sp ace pr oficient dat at yp e in v er sion 7 and called it VARCHAR2. VARCHAR2 is t he basic st ring t y pe for an Or acle t able colum n. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re CHAR(n) Er r or han dling and except ions I nt er - pr ocess com mu nicat ions This t y pe is used t o st ore a f ix ed- lengt h st r ing. I n ser t s w ill r ight - p ad blank s t o t he v alue if t he iv ser e const r aint s,isincluding , utnique, f or d eign k ey, ch eck , and lengt hDeclar of t heat in t ed value less t han ptrim h e ar lenygtk heyof he CHAR eclar at ion—t h is im p m actuch s m or e pr ogr am m er s w r it ing SQL w it h WHERE clauses wh o d o not exp ect colu mn v alues t o b e pad ded. Th is dat at y pe is r ar e. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] NCHAR(n), NVARCHAR2(n)

[ Team LiB ] These t y pes ar e used on ly t o st or e Unicod e ( un ified encodin g) char act er dat a, w hich is app licable f or Or acle applicat ions t h at sup por t m u lt ip le lan guag es.

1.5.2 Number

NUMBER, NUMBER(a), NUMBER(a,b) •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens This is a colu m n t y pe used f or st orin g n um ber s. Do n ot u se p r ecision par am et ers f or st or ing v alues of unk now n r ange. For t h e follow ing, w e can st or e a n um ber w it h vir t u ally an y m agnit u de in t he colum n AMOUNT. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

CREATE TABLE TEMP (AMOUNT NUMBER); INSERT INTO TEMP VALUES (0.12345); INSERT INTO TEMP VALUES (12345.1209); Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tThe eaches you w ou nesen eed tt so pr knecision, ow t o build an ber d com dat ab ases f or pyaram our bet usiness. p ar amet erhat " a"y repr t he trob ot alust num of plex p laceholder s. The er " b" r ep r esent s scale, p laces t o t he r igh t of t h e decim al point . So if you r field' s dom ain is t he age Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake of a p er son t hen you w ould use t h e follow ing t o st or e any t hr ee- d ig it w hole n um ber : adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y CREATE TABLE TEMP (age NUMBER(3)); Com plex r ule enf orcem en t Shou ld ou be or am ing un st ock p r ices w it age h am ax uimres u m of a m illion d ollar s ( seven places t o t h e PL/ySQL p rst ogr it s and langu f eat left of t he decim al point ) and f our places t o t he r ight of t he decim al p oin t , y ou wou ld u se: Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions CREATE TABLE TEMP (PRICE NUMBER(11,4)); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Scale is opt ional and, if n ot u sed, t he v alues ar e st ored as w hole n um ber s. Fr act ions, w hen Pr ogr am ing rou Oracle igger and est St or Pr oced , Thspecif ir d Edyitaion , is an inv aluable r esou rce insert ed,mare ndedTrt o t hesnear wed hole nu mbureres. To scale only , use: for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] CREATE TABLE TEMP (PRICE NUMBER(*,4));

[ Team LiB ]

1.5.3 DATE Types

DATE

The D ATE t yp e st ores d at e and t im e—som e d at abases separ at e t h is int o t w o t y pes, a t y pe for t he dat e an d a t y pe f or a t im e. For Or acle, t he DATE t y pe is a calend ar dat e and t ime—all in one. I n some applicat ions t he t ime of day is ir relevan t —ju st t he dat e, hence an app licat ion t o nofotContent show st he t im e b ut it is alw ays t here. Th er e ar e n um er ous built - in •m ight choose Table fu ogr nctam ions on Or dat pes t hat PL/Stor SQL for , such Pr m ing a cle e ®t yTr i gger s and e d can P roceper dure s, m Thir d Edi tias on com pu t at ions t o det er mine t he last day of t he pr eviou s m ont h. DATE arit h m et ic is also sup por t ed. You can easily build on By Kevin Owens exist ing dat e fun ct ion s and cr eat e a PL/ SQL libr ar y of dat e operat ion s t ailored t o you r app licat ion. Pub lish er: Prent ice Hall PTR

The d ef ault display of a D ATE colum n is DD- MON- YY. This default display can b e chang ed Pub Dat e: Decem ber 0 5, 2 003 w it h an ALTER SESSI ON com m and. To display D ATE v alues show ing hou rs, m inu t es, SBN: 0- 13 -0 850 33 -0 secondIs: Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t ALTER SESSION SETesNLS_DATE_FORMAT='DD-MON-YYYYhh24:MI:SS'; Kevin Ow ens ex plor PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: TIMESTAMP, TIMESTAMP(a) View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t The TI MESTAMP d at a t y pe is deriv ed f r om t he D ATA t y pe. I t repr esent s t im e w it h t h e same PL/ SQL p r ogr am un it s and langu age f eat u res pr ecision as DATE including a fr act ional secon d' s field. The TI MESTAMP for m at is: Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions 28-JUL-03 01.25.56.000122 PM Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e TI MESTAMP can b e declar ed w it h an opt ion al par am et er . Th e par am et er " a" r epr esent s t he nu mbam er m of ing digit s includ in st he actor ion t of he, tTh imirest amitpion . , is an inv aluable r esou rce Pr ogr Oracle Tr ed igger andf r St edalPrpar oced ur tes d Ed for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE INTERVAL DAY TO SECOND, INTERVAL YEAR TO MONTH

TI MESTAMPS can in cor por at e t im e zon es. Ap plicat ion s spr ead ov er mu lt iple t im e zones ar e likely t o use dat e colum ns of t his t y pe. The I NTERVAL t yp e r ep resent s a t ime diff er ence t o a par t icular signif ican ce. Th e follow ing cr eat es a t ab le w it h colum ns of each t y pe.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE TABLE times (d1 TIMESTAMP WITH TIME ZONE, d2 TIMESTAMP WITH LOCAL TIME ZONE, Pub lish er: Prent ice Hall PTR d3 INTERVAL DAY TO SECOND, PubINTERVAL Dat e: Decem ber 0 5, 2TO 003 MONTH); d4 YEAR I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

1.5.4 Large Objects Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake CLOB, BLOB, adv ant ag e of OrNCLOB acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: Use a CLOB t o st ore lar g e- char act er obj ect s. Th e lim it is four gigaby t es. A VARCHAR2 is View const r aint h ear dat ion ar colum y limit ed t o in 4,g000 char actserin s. tCh actaerdict - based ns need in g mor e t h an four gigaby t es should be CLOBs. Com plex r ule enf orcem en t Use t he BLOB t o st ore f our g igaby t es of binar y d at a. PL/ SQL p r ogr am un it s and langu age f eat u res A st u dent wr it ing sam ple can b e a colum n in t he st ud en t t ab le. I f w r it ing sam p les ar e Dat pes ex and comp osit st r u ct u re t hey ar e CLOB- t y pe colum ns. The t able and colum n docum entast yt hat ceed 4, 00 0 echar act ers ar e creat ed w it h t h e follow ing: Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e CREATE TABLE student_writting_samples (student_id Pr ogr am m ing OracleVARCHAR2(10), Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce writing_sample CLOB)); for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. Man ip ulat ion [ Team LiB ] of t he CLOB is t hr ough a CLOB/ BLOB API . This API is t h e Or acle b uilt - in packag e DBMS_ LOB. An ap plicat ion m anipu lat es t he obj ect by f irst select in g t he CLOB in t o a PL/ SQL obj ect . The CLOB/ BLOB is a pr iv at e t yp e. Operat ion s ar e r est r ict ed t o t he API . Th e follow ing PL/ SQL scr ipt p r in t s t he leng t h of t he st ud en t w r it ing samp le.

[ Team LiB ]

DECLARE v_writing_sample CLOB; the_length INTEGER; BEGIN SELECT writing_sample INTO v_writing_sample FROM student_writing_samples WHERE student_id = 'A101'; dbms_lob.open(v_writing_sample, dbms_lob.lob_readonly); the_length := dbms_lob.getlength(v_writing_sample); dbms_lob.close(v_writing_sample); Table of Content s dbms_output.put_line(the_length);



Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

END;

By Kevin Owens

BLOB is a four - gig aby t e obj ect t hat is int ended for st or ing bin ary im ag es. BLOB ob ject s are Pub lish ice Hall m anipu later:edPrent using t hePTR built - in pack age DBMS_ LOB. Pub Dat e: Decem ber 0 5, 2 003

NCLOBI SBN: t y pes st or e fou r - gigaby t e Unicode char act er obj ect s u sin g t he Nat ional Char act er set . 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin BFILEOw ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our An obj ect need not ph ysically b e st ored in a colum n. Rat her , a colum n can act as a r efer en ce dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he t o an ob ject . Such an object w ou ld b e a f ile on t h e host disk . A st udent w r it in g sam ple can be bu sin ess evolv es. Topics cov er ed include: st or ed com plet ely in a colum n as a CLOB. Alt er nat iv ely , a w r it in g sam ple can r em ain on a file ser v er, yet be accessib le t hr oug h SQL. Th is requ ir es t h at t h er e b e a BFI LE colu mn t y pe. Th e BFI LEView act sinas a r efer en ce t o t thhee dat ex taerdict nal ion f ile. g const r aint s in ar Th y e ext er nal f ile con t ent can be accessed usin g t he DBMS_LOB API . Com plex r ule enf orcem en t The f ollow in g cr eat es a t ab le for st ud en t w r it ing samp les an d in ser t s an ext er nal file r ef erence. The is just a page oin ft eat er tuores t h e file JOHN. DOC t hat p hy sically r esides in PL/ SQL p rBFI ogrLE amcolum un it s nand langu t he dir ect or y D: \ STUDENT_ FI LES. The cr eat ion of t he Or acle dir ect or y r equir es t he CREATE ANY DDat I RECTORY a t y pes and p riv ileg comp e. osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar iv e constDIRECTORY r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch CREATE OR at REPLACE m or e STUDENT_FILES AS 'D:\student_files'; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce CREATE TABLE student_writing_samples for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly (student_id VARCHAR2(10), int ellig en t , com plex dat abases. writing_sample BFILE); [ Team LiB ] INSERT INTO student_writing_samples (student_id, writing_sample) VALUES ('A101',bfilename('STUDENT_FILES','John.doc'));

[ Team LiB ] BFI LE object s ar e m anipu lat ed using t he DNMS_LOB API . To pr int t he lengt h of t h e w r it in g sam ple:

DECLARE v_writing_sample BFILE; the_length INTEGER; BEGIN SELECT writing_sample INTO v_writing_sample FROM student_writing_samples WHERE Table student_id • of Content s= 'A101'; Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

dbms_lob.fileopen (file_loc => v_writing_sample, open_mode => dbms_lob.file_readonly);

By Kevin Owens

Pub lish er: Prent ice Hall PTR

the_length := dbms_lob.getlength(v_writing_sample);

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

dbms_lob.fileclose(file_loc => v_writing_sample); Pages: 44 8

dbms_output.put_line(the_length); END; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 1.5.5 t eachesXML you wType hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: XMLType View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t The XMLTYPE as ram eleased it h langu Or acleage 9 i Release PL/ SQL pwr ogr un it s wand f eat u res 2. Th is t y pe is used t o st or e XML docum ent s as at t r ibut es t o an en t it y. For ex am ple, st udent t r anscript s can b e st ored as XML docum entas.t yTh is and docum en tosit w ou Dat pes comp e ld st rbuectan u reat t r ib ut e of t h e st udent and exist in a STUDENTS t able as a single colum n. The t ab le for a st udent and t r anscript is: Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m orTABLE e CREATE student_transcripts (student_id VARCHAR2(10), Prtranscript ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce SYS.XMLTYPE); for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. The XMLTy pe has built - in m et h ods. The follow in g st at em ent in ser t s a t r anscr ipt for a st ud en t [w it Team ] h t w oLiB classes.

[ Team LiB ] INSERT INTO student_transcripts (student_id, transcript) VALUES ('A101', sys.XMLTYPE.createXML('' ||'' ||'Math 101' ||'A' ||'' ||'' ||'English 102' ||'A' ||'' ||'')); •

Table of Content s

The ollow in g st atsem enStor t r et ns t dure he sts,udent and t r anscr ip t r ecord . Pr ogrfam m ing OrSELECT a cl e ® Tr i gger and e dur P roce Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Dat e:10000 Decem ber 0 5, 2 003 setPub long I SBN: 0- 13 -0 850 33 -0 SELECT student_id, Pages: 44 8 p.transcript.getClobVal() FROM student_transcripts p;

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d XML docum s can ben reed eadt ofr om a host f ile and loaded in t o plex a CLOBt yp e colu t hen t eaches youent w hat y ou kn ow t o build rob ust an d com dat ab ases f ormyn. ourI t bcan usiness. be n avig at ed in PL/ SQL u sin g t h e XML bu ilt - in pack ages t hat f ully su ppor t t he D ocu ment Ob jecteasyMod el DOM) API or XML docum Using t o-( follow inst rfuct ions an d ex ent am s. ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov erTypes ed include: 1.5.6 LONG and RAW View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res LONG Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions Or acle ppor t for larions ge ob ject s in ver sion 8. Prior t o t h is release, st r ings t hat I ntint err-oduced pr ocesssu com mu nicat exceed ed t h e boun ds of a VARCHAR2 t y pe cou ld be man ipulat ed, w it h lim it ed f unct ionalit y , using Declar a LONG at y pe. St rs, ingincluding s t hat ex p ceed t he of a VARCHAR2 shou bem uch at ivdat e const r aint rim ar y klim ey ,itus nique, f or eign k ey, chld ecknow , and m anipu lat ed as a CLOB using t he built in DBMS_LOB packag e. m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] RAW, LONG RAW

[Sim Team ilar tLiB o t h] e LONG t y pe, t he RAW an d LONG RAW dat at y pes serv ed a useful pur pose p rior t o LOB su ppor t w it h Oracle 8. The RAW and LONG RAW t y pes w ere used f or m anipulat in g binar y d at a—t he Or acle b uilt - in p ack age, D BMS_LOB, pr ov ides adv anced sup por t f or m anipu lat in g binar y dat a.

1.5.7 ROWID Type

ROWID, UROWID •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

A ROWI D con t ains com posit e infor m at ion t hat allow s Or acle t o ident ify , f or m a sing le ROWI D v alue, w here a specif ic r ow in a t ab le is locat ed ( i.e. , t h e t ablespace, file, dat abase b lock , and specif ic locat ion w it hin t hat block ) . You can d eclar e a t ab le wit h a colu mn of t y pe ROWI D, Pub lish er: Prent ice Hall PTR pop ulat e t h at t ab le wit h ROWI D v alues, and ext r act in for m at ion ab out t he v alue u sin g t h e Pub Dat e: Decem ber 0 5, 2 003 Or acle built - in pack age DBMS_ ROWI D. The UROWI D is a u niv er sal ROWI D st r uct ur e t h at 0- 13 -0 850 33t -0 supp ortI SBN: s nonOracle ab les. Pages: 44 8

[ Team LiB ]

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

1.6 Behind Tables What is a t able? I s it a file, a block , or a st r eam of by t es? Her e w e look at t ables logically and ph ysically .

1.6.1 Application Tablespaces All t ab le dat a is ult imat ely st or ed in host operat in g sy st em files; but , t he in ser t ion of r ow s nev er sp ecifically ident ifies a host f ile. •

Table of Content s

The ir stm ing st epOris e an intStor er me dedPiat e dure logical layer a t ablesp ace w it h a CREATE Pr ogrfam a clteo® creat Tr i gger s and roce s, Thir d Edi called ti on TABLESPACE st at em ent . Th is st at em ent includes t h e host p at hnam es of one or m ore h ost By Kevin Owens files t hat ar e t o be cr eat ed. The CREATE TABLESPACE st at em en t cr eat es t he f iles m ent ioned in t he st at em en t , f orm at s t he f iles, and st or es in for m at ion in t h e Or acle d at a d ict ionar y . Th e dat a dict ionar y inf orm at ion t r acks t he f act t hat a t ab lespace is m ade up of sp ecific f iles. Pub lish er: Prent ice Hall PTR

Pubt he Dat te:ablespace Decem ber 0 5, 003 ed, t he CREATE TABLE st at em ent can r efer en ce t he t ab lespace On ce is 2creat I SBN: 013 -0 850 33 -0 nam e in t he cr eat e st at ement . Fr om t his point on, Or acle w ill u se t he f iles of t h at t ab lespace 44 8e. Figur e 1- 3 illust r at es t his ar chit ect ur e show ing t hat t ables and t ab lespaces for rowPages: st orag ar e logical ent it ies w hereas t h e dat af iles ar e t h e ult im at e ph ysical com ponent .

Figu r e 1 - 3 . Tabl es i n a Tabl espa ce . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions To r eplicat e t he en vir onm ent in Figur e 1- 3 cr eat e t he t ablesp ace, t h en t h e t able. The followDeclar ing creat a t ablesp STUDENT_DATA es f 10 M of kdey, isk ch space. The m uch at ives e const r aintace s, including p rim ar y and k ey , allocat u nique, or eign eck , and pr esum mor pt eion is t hat t his f ile does not ex ist ; in fact , t his st at ement w ill fail im m ediat ely if t he file ex ist s pr ior t o st at em en t ex ecut ion . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] SQL> CREATE TABLESPACE student_data DATAFILE 2 'D:\student_data.dbf' size 10M;

Tablespace [ Team LiB ] created. To cr eat e a STUDENTS t able in t he STUDENT_DATA t ablesp ace:

SQL> CREATE TABLE students 2 (student_id VARCHAR2(10), 3 student_name VARCHAR2(30), 4 college_major VARCHAR2(15), 5 status VARCHAR2(20)) TABLESPACE student_data; Table created. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

OtKevin h er t Owens ables can b e added t o t he STUDENT_D ATA t ab lespace. The st ud en t d em o is descr ibed By in Ch apt er 4. All t he dem o t ab les ar e cr eat ed in a STUDENT_ DATA t ab lespace. A sing ion u su ally has all t ab les in one t ablesp ace. Th er e ar e circum st ances w her e Puble lishapplicat er: Prent ice Hall PTR m ultPub iple t ab lespaces ar e used . Mu lt ip le t ablesp aces ar e d riv en b y a v ar iet y of issues including Dat e: Decem ber 0 5, 2 003 high ly dem anding p hy sical st or age r equir ement s and par t it ioning . The f ollowin g sum m ar izes I SBN: 0- 13 -0 850 33 -0 som e rem aining t opics on t ablespaces. Pages: 44 8

Ther e is a st an dar d, k now n as t h e Opt im al Flexible Ar chit ect ur e ( OFA) . Th e OFA st andar d r ecom m en ds t h at d at abase files f it int o a d ir ect ory st r uct u re wh er e t h e par ent ect or y neame t he age samcom e nam e as he dat ab nam e, plus ot herand r easonab le ex per t Ef fectdir ively creat an disman plex datt abases wase it h Or acle! Sy st ems dat ab ase oremOrent ioned ex am en t ion on lyage t o (sim plify Kevinconsiderat Ow ens exion plors.esThe PL/af SQL, acle's answ er ple t o tvhiolat e St res uctt his ur edconv Query Langu SQL) , an d t heyou ex am ple.y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. t eaches w hat d at afile D: \ inst st u dent dat a. d am id nples, ot extist ior t oprtesent he CREATE TABLESPACE UsingThe easyt ofollow r uct _ions andbf d ex hisprbook s t echniq ues t o t ake stag at ement This feat f ile ur is es cr eat edas d urt rig inggers t he and ex ecut ion of h e CREATE TABLESPACE adv ant e of Or. acle such st ored prtoced ur es- f eat u r es t hat allow y our at ement . I t por is patossible t o cr eat e awthich ablesp ace on tan ex istage ing and dat afile—t dat abst ases t o incor e bu siness r ules ar e easy o man m odif yhis asr teq heuir es a clause in t h ecov synert ax. bu sin REUSE ess evolv es. Topics ed include: A t ablespace can consist of m ult iple files. For ex am ple, if you n eed 20M y ou can hav e g const tView w o 1in0M files.r aint s in t h e dat a dict ion ar y Comdplex r ule in enft he orcem en t TABLESPACE st at em ent ar e f or mat t ed by Or acle. You' ll The at afiles CREATE not ice t h at a CREATE TABLESPACE st at ement on a 2 G d at afile t ak es relat iv ely long er PL/ p r ogr unThis it s and age f eat ufres t hatSQL a 2M dat am afile. is b langu ecau se Oracle orm at s t he dat afile using it s ow n int ern al block st r uct ur e. Dat a t y pes and comp osit e st r u ct u re The af or em ent ioned exam ple is sim ple and m ay im ply a st rict ar chit ect ur e—su ch as Er r or han and w except dealing w dling it h space h en yions ou fill up 10 M of d at a. The t ablesp ace m od el is highly f lex ible. You can ad d f iles t o an exist ing t ablespace, resize a d at afile, m ove a dat af ile t o an ot her I nt er - pr ocess com mu nicat ions dr iv e and r esize it , or allow dat af iles t o aut o- ex t en d—all w it hou t t ak ing dow n t h e dat ab ase. Th e ph ysical layou t of an Or acle dat ab ase is h ighly f lex ible. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e A d at afile can ser v e one an d on ly one t ab lespace. You will n ev er , and cannot possibly, hav e cond it ion s w here a dat afile is " t ied" t o m or e t han one t ablesp ace. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly An Or acle u ser alw ay s has a DEFAULT t ablesp ace. So, if y ou do not sp ecify a t ablespace int ellig en t , com plex dat abases. nam e, t h at t ab le is cr eat ed in y our d ef ault t ablespace. You can g et y our d ef ault t ablespace nam e by quer yin g t h e dat a dict ionar y v iew USER_USERS. [ Team LiB ]

SQL> default_tablespace FROM user_users; [ Team LiB SELECT ] DEFAULT_TABLESPACE -----------------------------USERS

A t able is creat ed in a sin gle t ablespace. Ex cept ion s t o t his ar e par t it ioned t ables w here indiv idual par t it ions ar e cr eat ed in separ at e t ablespaces. While a t able is cr eat ed in one t ab lespace, t he in dexes f or t hat t able ar e of t en in a sep arat e t ablesp ace. Th e DDL f or t he dat a m od el demo in Ch apt er 4 cr eat es all index es in t he t ab lespace STUDENT_I NDEX.

1.6.2 DataTable Dictionary • of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

The ex ecu t ion of a CREATE TABLE st at em ent cau ses inf or mat ion t o be st or ed in t he dat a By Kevin Owens dict ionar y . The d at a d ict ionar y is t he t er m used t o descr ibe t ables and view s t hat exist in t h e SYSTEM t ablespace. The dat a dict ionar y is essent ially a reposit or y for Or acle t o t r ack inf orm at ion abou all ob Pub lish er: Prent icet Hall PTRject s creat ed in t h e dat ab ase. Th e infor m at ion t r ack ed in clu des: t he t able n am e, wh o ow ns t he t ab le, w h en it was cr eat ed, colum n nam es and dat at y pes, and t h e Pub Dat e: Decem ber 0 5, 2 003 t ablespace nam e t o w hich a t able b elong s. All PL/ SQL st or ed p rocedu re sour ce and com piled I SBN: 0- 13 -0 850 33 -0 code is st or ed in t he dat a d ict ion ary . Th e dat a dict ionar y t ables and v iew s of t h e SYSTEM Pages: 44 8 t ablespace ar e illu st r at ed in Figur e 1- 4 .

Figu r e 1 - 4 . Da t a Di ct iona r y an d Sy st em Tabl espa ce. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch The dm ator ae d ict ion ary con sist s of Or acle t ables and v iew s t h at ar e const r uct ed fr om SELECT st at ement s against t he base t ab les. Th e dat a dict ionar y view s pr ov ide t h e at t r ibut es of an y Pr ogr m ing igger s and St or ed Pr ocedcan ur esbe , Th d ied Ed ittion , iseran inv r esou obj ectam creat ed.Oracle Th e v Tr iew USER_TAB_COLUMNS quirer o det m in e aluable t he colum n rce for d ev elopers, er s, yand pr oj leader look in gt colum t o b uild an d mion aint namdat es abase of a t able. The datdaesign dict ionar v iew t oect q uery fors st ud en n definit s ain is t r uly int ellig en t , com plex dat abases. USER_TAB_ COLUMNS. [ Team LiB ] t ablespace is cr eat ed w hen t he d at abase is f ir st cr eat ed . The SYSTEM t ablespace The SYSTEM and dat afiles are generat ed as par t of t he CREATE DATABASE st at em ent . Applicat ion t ablespaces, such as STUDENT_ DATA, can b e add ed t o t he d at abase at any t im e.

The f ollow [ Team LiBin]g SQL* Plu s session cr eat es a STUD ENTS t ab le. A qu er y of t h e dat a dict ionar y v iew USER_TAB_COLUMNS show s t he colum n nam e and colu m n t yp e of all colu mn s in t he STUDENTS t able.

SQL> CREATE TABLE students 2 (student_id VARCHAR2(10), 3 student_name VARCHAR2(30), 4 college_major VARCHAR2(15), 5 status VARCHAR2(20)) TABLESPACE student_Data; Table created. •

Table of Content s SQL> SELECT table_name, column_name, data_type Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on 2 FROM user_tab_columns By Kevin Owens table_name='STUDENTS'; 3 WHERE

TABLE_NAME COLUMN_NAME Pub lish er: Prent ice Hall-----------------------------PTR ---------------STUDENTS Pub Dat e: Decem ber 0STUDENT_ID 5, 2 003 STUDENTS STUDENT_NAME I SBN: 0- 13 -0 850 33 -0 STUDENTS COLLEGE_MAJOR Pages: 44 8 STUDENTS STATUS

DATA_TYPE ---------VARCHAR2 VARCHAR2 VARCHAR2 VARCHAR2

To see t he t ablesp ace in w hich t he STUDENTS t able ex ist s, u se Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv antSELECT ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SQL> tablespace_name dat2ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he FROM user_tables bu 3 sin ess evolv es. Topics cov er ed include: WHERE table_name='STUDENTS'; TABLESPACE_NAME View in g const r aint s in t h e dat a dict ion ar y -----------------------------STUDENT_DATA Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res The f ollow in g sh ows t he d at afiles and file sizes associat ed w it h t he STUDENT_ DATA t ablespace. y select s ef rom t he D BA_DATA_FI LES v iew an d requ ir es t h at y ou hav e Dat a t yThis pes qu ander comp osit st r u ct u re t he DBA r ole or SELECT_ CATALOG_ROLE r ole. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m orfile_name e column format a50 SQL> SQL> SELECT file_name, bytes Pr ogr m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce 2 am FROM dba_data_files for3datWHERE abase dtablespace_name='STUDENT_DATA'; ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. FILE_NAME [-----------------------------------------Team LiB ] E:\ORACLE\ORADATA\ORA10\STUDENT_DATA01.DBF

BYTES -------5242880

[[ Team Team LiB LiB ]]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Chapter Two. Interacting with Oracle 2. 1 SI MPLI FY SQL* PLUS FOR YOURSELF ON WI NDOWS 2. 2 CONNECTI NG 2. 3 CONNECTI NG TO AN I NFRASTRUCTURE 2. 4 DI SCONNECTI NG 2. 5 COMMAND LI NE •

Table of Content s

Pr ogr am mCHANGES ing Or a cl e ® ON Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on 2. 6 THE COMMAND LI NE By Kevin Owens

2. 7 SCRI PTS 2. 8 SCRI PT OUTPUT

Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003

2. 9 COMMAND LI NE ARGUMENTS I SBN: 0- 13 -0 850 33 -0

2. Pages: 10 SQL* 44 8 PLUS WI TH KORN SHELL 2. 11 BATCH COMMAND FI LES 2. 12 SQL* PLUS WI TH ACTI VE STATE PERL Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin2.Ow exLEGES plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 13ens PRI VI t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 2. 14 DUAL Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 2.ag 15eAUTOTRACE dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sinp ess evolv Topics er ted include: The ur pose ofes. t his ch aptcov er is w ofold : dem onst r at e t h e int eract iv e feat u res of SQL* Plus an d, show h ow t o incorp orat e SQL* Plu s int o ot her scr ipt in g lan guag es su ch as Kor n Shell and Perl. View in g const r aint s in t h e dat a dict ion ar y [ Team LiB ] Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.1 Simplify SQL*Plus for Yourself on Windows I n t his sect ion w e focus on m et hod s t hat simp lif y SQL* Plus scrip t f ile or g anizat ion. You w ill event u ally be cr eat in g, sav in g, an d r et r iev ing SQL* Plus scrip t s. You w an t t h e scr ipt s t o be sep arat e fr om ot h er files; you w ant t o kn ow exact ly w her e t hey ar e an d b uild an d mod ify t hem w it h out a lot of h ead ach es. SQL* Plus is a scr ipt ing lang uage t hat in clu des com m and f ile su ppor t . Th is t ext en cour ages t he use of com m and f iles, also called SQL scr ipt s. You r SQL* Plus scrip t s w ill event u ally cont ain m ult iple SQL DML st at em en t s, CREATE t able st at ement s w it h const r aint clau ses, and Or acle st ored pr oced ur es and t r ig gers w rit t en in PL/ SQL. •

Table of Content s

When ouinginOr st aall acle, he full t er pr isetilicensed dat abase or j ust t he desk t op Pr ogr amym cl e Or ® Tr i ggerw s het andher Storit e 'dsPtroce dureen s, Thir d Edi on client t ools, y ou w ill b e able t o launch SQL* Plu s fr om y our desk t op t hr ou gh START - > By Kevin Owens PROGRAMS. W hen y ou use t his met hod t o r un SQL* Plu s, you r defau lt d ir ect ory ( i.e. , t h e dir ect or y f or saved and r et riev ed script s) is t he sam e as t h e Or acle " bin" dir ect or y . This is n ot v er yPub conv enient —yHall ou PTR wan t t o k eep you r scr ipt s in a sep arat e wor k ing dir ect or y . You can lish er: Prent ice ov erPub r ide t h e defau lt " bin " dir ect ory and sav e a SQL scr ipt t o an ot her dir ect or y —t his r equ ir es Dat e: Decem ber 0 5, 2 003 includin g t h e fu ll pat h nam e w it h t he SQL* Plus SAVE com man d. You can ru n SQL scr ipt s t h at I SBN: 0- 13 -0 850 33 -0 exist in a nond ef ault direct or y if you t y pe a fu ll pat h nam e in t he r un com man d. Th ese Pages: 44 8 ov er r ide m et hods are in con venient , and t her e ar e bet t er t ech niqu es t o be discussed shor t ly . On e appr oach t o ov err iding t h e defau lt dir ect ory is t o cr eat e a deskt op shor t cut for SQL* Plu s and designat e a START- I N direct or y. The START- I N dir ect or y w ill be t h e new d ef ault direct or y for SQL* Plucreat s screiptan s.dWman it hout ecifplex ying dat a stabases ar t - in dir ory , all Sy sav scrip defau lt t oex t he Ef fect ively agesp com w itect h Or acle! sted ems andt s dat ab ase per t Or acleOw " bin" ores y —a ir ect or w it h h und reds her Orur acle files. Langu age ( SQL) , an d Kevin ensdir exect plor PL/dSQL, Oryacle's answ er t o of t h eotSt r uct ed Query t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Let ' s do t his now . Using Wind ows Ex plor er , cr eat e a " w or k in g direct or y" w her e you w ish t o st or e you r libr y of SQL* Pluions s scr an iptds. ex For amptle, eat e pr t he dir ect or y: ues t o t ake Using easyt o-ar follow inst r uct amex ples, his crbook esent s t echniq adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y C:\MY_SQLPLUS Com plex r ule enf orcem en t Next , cr eat e a desk t op shor t cut f or SQLPLUSW. EXE. Th is pr ogr am is in t he Or acle " b in" p r ogr am un it st he and langu f eatshor u res dir ectPL/ or ySQL . Then r ight - click n ew ly crage eat ed t cut icon fr om t h e deskt op , select " Pr oper t ies, " an d select " Shor t cut " —t his is w her e y ou set t he " St ar t in" d irect or y. Set t he t y pes ositt he estdir r u ect ct uor rey y ou ju st creat ed, ( i. e. , C: \ MY_SQLPLUS) . The " St ar tDat in "a f ield t oand t he comp pat h of shor t cut cr eat ion st ep is show n in Figur e 2- 1 . Er r or han dling and except ions

re 2- 1. I nt er - pr ocess com muFigu nicat ions

SQL* Plus Sh or t cu t .

Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Aft er y ou t y pe t h e pat h nam e in t he " St ar t in " f ield , select t he " Apply " b ut t on , t hen t he " OK" bu t t on,easyan d t you 'r e don e. r By doingant his ar e able o savepran d ret e scrip o, an d Using o- follow inst uct ions d exyou am ples, t hist book esent s rt iev echniq uest st ointt ake fr om , a dedicat ed " St ar t in" direct or y—not hing else but y our script s ex ist s her e. You can ygo adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow our tdat o tab hisases dir ect ory t o copy an d edit scr ipt s. You hav e n ow m ade t h e dir ect or y C: \ MY_SQLPLUS, t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he ybu our er sonal ev elopm t code ar y , and int egr at ed it int o SQL* Plus. sinpess evolv des. Topicsen cov er ed libr include: The af or em ent ioned pr ocess is n ot n ecessar y in a UNI X env ir on ment . I n UNI X y ou can " cd" ( chang e dir or y com msand) an ya UNI View inect g const r aint in t hteo dat dict X iondir arect y or y, su ch as a dedicat ed SQL* Plu s cod e libr ar y, an d in vok e SQL* Plus by t y ping j ust t h e ex ecut able n ame on t he com man d line—t h is w or ksCom becau se rtule he enf SQL* Plus en p rog plex orcem t ram is in y our $PATH. Fr om t his p oin t , all f iles f r om y our SQL* Plus session are aut om at ically sav ed int o t he cu rr ent w ork ing dir ect ory ; t hat is, t he dir ectPL/ or ySQL f r omp rwogr hich ou itinv oke langu SQL* age Plu s.f eat u res amy un s and You wDat ill see w o ver s ofosit SQL* a t ytpes andsion comp e stPlus r u ct uinreyou r Wind ows Or acle " b in" direct or y: SQLPLUS. EXE and SQLPLUSW. EXE. Use SQLPLUSW—t his is f or ever yd ay int er act iv e use. I t b eg ins w it h a r or han dling and pop upErbox p rom pt in g youexcept w it h ions log in in for m at ion. Th is ver sion r uns SQL* Plu s in a scr ollable w indow —t h is is v er y easy t o w or k w it h. The SQLPLUS.EXE v er sion r uns in a " DOS" w in dow , nt er - pr ocess mu nicat w ions black Iscr een, an d n com o scrollable ind ow . You w ould u se t his v ersion of SQL* Plu s t o lau nch a SQL scr ipt fr om a DOS bat ch file or call SQL* Plus wit h com m and lin e ar gum ent s f r om a iv e const r aint including k ey ,ion u nique, scr ipt Declar in g lanat guag es such ass,Per l—illust rpatrim edariny Sect 2. 1 2. f or eign k ey, ch eck , and m uch m or e Aft er y ou creat e t he deskt op shor t cut and up dat e t h e st art - in d ir ect ory , y ou hav e a desk t op Pr ing Oracle Tr igger andFigur St or ed ur esa ,deskt Th ir dopEdwitition , is an invb aluable w itogr h tam he m SQL* Plus icon showsing. e 2-Pr2oced sh ows h not one, ut t hr ee,r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d ainever t r uly SQL* Plus icons. Here, each icon is a sh ort cut t o t he sam e SQL* Plus ex ecut abm le;aint how , int ellig en t , com plex dat abases. each h as a d if fer en t st ar t - in dir ect or y , w hich means t hat each has a separ at e " wor k ing dir ect or y . " Th is is one t echniqu e for " con quer ing and div iding" y our w or k in a Wind ow s [ Team LiB ] env iron ment . Again, t his is not necessar y in a UNI X en vir onm ent becau se y ou simp ly " cd " t o any w or k ing dir ect or y and on ce in t h at dir ect ory , y ou inv oke SQL* Plus. I n a Win dow s env iron ment , you m ay b e inclin ed t o separ at e w or k am ong v ar iou s dir ect or ies and t ie a SQL* Plus ex ecut ab le sh or t cu t t o t hese sep arat e w ork d irect or ies.

[ Team LiB ]



Figu r e 2 - 2 . SQL* Plus Sh or t cu t s on t h e De sk t op .

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

The t hr ee box es on t h e far righ t of Figur e 2- 2 r epr esent dist inct " St art in" dir ect or ies. One By Kevin Owens dir ect or y m igh t b e used t o st ore all t he CREATE t able scr ip t s f or y our app licat ion. This w ould include scr ipt s t o creat e t r igg er s, seq uences, an d in dexes. On e could be t he dir ect or y w her e y ouPub m aint ain all y our PL/ SQL st or ed pr ocedur es. One d irect or y w ould be used for ap plicat ion lish er: Prent ice Hall PTR st at ement t un ing—t his dir ect or y w ould include man y SQL* Plus list f iles w it h t he ex ecut ion Pub Dat e: Decem ber 0 5, 2 003 pat h s of t he man y SQL st at em ent s you ar e t un ing. I SBN: 0- 13 -0 850 33 -0

[ TeamPages: LiB ]44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.2 Connecting To p r oceed f r om t his p oint for w ard , y ou n eed an Or acle d at abase. Ther e ar e t w o b asic conf ig ur at ions. On e sof t w ar e config ur at ion is t o hav e ev er y t hing on one m achine; t hat is, t he Or acle dat abase an d client cod e can all b e on you r deskt op . An alt er nat iv e is f or y our Oracle dat ab ase t o b e on a sep arat e host , in w hich case y ou' re conn ect ing w it h SQL* Plus t o Or acle ov er a net w or k . I f you r Or acle sof t w ar e en vir onm ent is set up, you 'r e r eady t o con nect and b eg in ex ecut in g SQL. I f t his needs t o be d one y ou can begin w it h inst allin g t h e Or acle Clien t CD. This in st alls SQL* Plus an d ot h er ut ilit ies on y our desk t op t hat allow y ou t o int er act w it h a d at abase on t he •net w or k. An Table alt er of natContent e is t os inst all t h e Or acle Ent er pr ise CD. Th is giv es y ou t he en t er pr ise Pr ogr am m ing Or a cl e ® Tr i gger and d Pault roce dat dureabase. s, Thir d Edi ti on soft w ar e and op t ionally crseat esStor a de ef By Kevin Owens

For Wind ows en vir onm ent s, it is st r on gly r ecom m en ded t hat y ou set up a sh ort cut and a st ar t - in d irect or y, descr ibed in Sect ion 2. 1 . Once t his is d one, y ou can inv oke SQL* Plu s fr om t he Pub desk op.Prent ice Hall PTR lishter: Pub Dat e: Decem ber 0 5, 2 003

When y ou lau nch SQL* Plus fr om Wind ow s, you get a p opup w indow w it h inp ut fields f or a I SBN: 0- 13 -0 850 33 -0 usern am e, passw or d, and host st r ing—illust r at ed in Figur e 2- 3 . Pages: 44 8

Figu r e 2 - 3 . SQL* Plus Login . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re On ce y ou ent er t he user nam e, passw or d, and h ost st rin g y ou hav e a perm anent poin t - t or or han dling except ions point Er connect ion t o tand h e dat ab ase. On ce con nect ed , t he d at abase is at you r ser v ice t o pr ocess ever yt hing fr om d at abase qu er ies, t o CREATE t able st at em en t s, and st or ed pr ocedur e I nt er - pr ocess com mu nicat ions execut ion. Declar e const r aint including p rim , uor nique, f or eign k ey, ch eck m , and m uch ust be in For UNI X enat virivonm ent s, t h es,SQL* Plu s pr ogr ar amy kd ey irect y, $ORACLE_HOME/bin, m or e y our p at h. I n UNI X, y ou inv oke SQL* Plu s fr om t h e comm an d line b y t y ping t he pr ogr am nam e f ollow ed by an ar gum ent st rin g t hat con t ain s usern am e, passw or d, and host st r ing in Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce t he for m at show n nex t : for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] $ sqlplus username/password@host_string

[For Team LiB ] exam ple:

$ sqlplus scott/tiger@ora SQL> _

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.3 Connecting to an Infrastructure This sect ion illust r at es t he Oracle inf rast r uct ur e t o w hich you connect . Th e fir st par t , illust rat ed in Figur e 2- 4 , d iscusses t he poin t - t o- point connect ion you hav e w it h Or acle in a dedicat ed- ser v er env ir onm ent . Second , w e discuss t he in st an ce in fr ast r uct ur e, illu st r at ed in Figur e 2- 5 . Th is is all t ied t og et her w it h a discu ssion sur rou ndin g Figur e 2- 6 .

Figu r e 2 - 4 . Or a cl e De dicat ed- Se r v er M ode.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Figu r e 2 - 5 . Da t a base I nst a nce .

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions

Figu r e 2 - 6 . Da t a base I nst a nce w i t h Con ne ct i ons.

I nt er - pr ocess com mu nicat ions

Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]



Content s When y ou inTable vok e ofSQL* Plus y ou st art an int er act iv e pr ogr am , or pr ocess, t hat w ill id le, Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on w ait ing for you t o t yp e a com m and—SQL* Plus sp en ds m ost of it s t im e in an idle st at e w ait ing By forKevin you Owens t o t y pe in a SQL st at em en t . On ce you est ablish a con nect ion , t her e ar e act ually t w o pr ocesses: one is t he SQL* Plus p rog ram t o w hich y ou ar e int er facing , and t he ot her is an Or acle pr ocess t o w hich y ou hav e a p oint - t o- p oin t conn ect ion. This connect ivit y is illust r at ed Pub lish er: e Prent in t he Figur 2- 4icewHall h erPTR e w e see SQL* Plus as a separ at e pr ocess, dedicat ed t o serv icin g t he Dat e: Decem 2 003 SQLPub st at ement s tber hat0 5,y ou t y pe—t h is ot her pr ocess is Or acle. I SBN: 0- 13 -0 850 33 -0

Figur ePages: 2- 4 d44 ep8 ict s t hr ee user s each ru nning SQL* Plus. Each is r un ning a com m and lin e SQL app licat ion t hat has a dedicat ed conn ect ion t o an Or acle pr ocess. For each of t h ese p oin t - t opoint scen arios, t h e par t ner ing Or acle p rocess begins t o r un w hen t he u ser inv ok es SQL* Plu s w it h a user nam e and passw ord . Ef fect ively an d tman com plex dat abases w ithost h Or st acle! ems ab ase When SQL*creat Plus eaccep s a uage ser nam e, passw ord , and ring Sy , itstat t emand p t s tdat o con nectex t oper ant Kevin ex plor acle's er is t om t hade e Stan r uct edusern Query ( SQL)d, ar aned Or acleOw datens abase in stes anPL/ ce. SQL, OnceOr t he connansw ect ion d ur the amLangu e andage passwor tveaches y ou eed t o kn ow t o is build rob ust anon d com plex abSQL* ases Plu f or sy session our b usiness. alid at edyou , t hw e hat separ at en Oracle pr ocess est ablished b eh alf of dat t hat . Using easyfollow an d am ples, t hisr ealbook s t echniq ues Dat ab ase intsto-ance is inst t he rtuct er mions u sed t o ex d escr ib e t he t impre esent pr ocessing fr am ewt oortkake of a adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat allow y oure r unn ing dat abase. This f r am ew or k consist s of Or acle b ack gr oun d pr ocesses t h at com m unicat dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he w it h each ot her t h rou gh shar ed m emor y . bu sin ess evolv es. Topics cov er ed include: Pr ior t o an y users con nect ed int o Or acle, w e h ave a dat ab ase in st ance t hat is open, an d w hich gr aphically ( see Figur e 2- 5 ) means we hav e t hr ee m ain com ponent s: View in g const r aint s in t h e dat a dict ion ar y Com plex enf t 1 . Num erou sr ule back grorcem ound en p rocesses. SQL p r ogr un it sedand langu f eatt he u res 2 . PL/ A lar ge ch unkam of shar mem or y age called Sy st em Global Ar ea ( SGA) , w hich can r ange up w ard f rom 25M. Dat a t y pes and comp osit e st r u ct u re 3 . Disk space, w hich consist s of m any t y pes of f iles. We r efer t o t he com plet e set of files on Er r oras han except ions disk " t hdling e datand ab ase. " pr ocess com nicat ions Figur eI nt 2-er5 - illust r at es a dmu at abase inst ance t h at is an open dat ab ase t o w hich user s can connect . Figur e 2- 5 j ust sh ow s t he d at abase inst ance and d at abase files—no u ser s ar e Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch connect ed in t his illust r at ion. m or e Keep in m in d t hat Figur e 2- 5 is a gener alizat ion of t h e Or acle archit ect ur e and it is Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce gener alized so as t o not clou d t his issu e of con nect iv it y w it h t he com plex f ram ew ork of an for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Or acle inst ance. The Or acle ar ch it ect u re is a t opic u su ally reser v ed f or book s on Or acle int ellig en t , com plex dat abases. dat ab ase adm inist rat ion . [ Team LiB ] Assu m e w e hav e an Or acle in st an ce open an d no u ser s ar e connect ed . First , w e st ar t SQL* Plus as an int er act ive p r ogr am t hat init ially r uns as a st and - alon e pr ogr am . I t is st an dalone u nt il y ou giv e it an Or acle user nam e, p assw or d an d host st r ing—t hen t h er e is som e act ivit y . SQL* Plus t hen sends a conn ect ion requ est t o a specif ic Or acle p rocess, t he Or acle

list en er .LiB Th e] Or acle list ener is a h ost pr ocess, or W in dow s serv ice, dedicat ed t o ser vicing [ Team inbou nd connect ion r equ est s. I f t he u ser nam e and p assw or d ar e v alid, t h e list ener sends back a su ccessf ul r et ur n code. A d ed icat ed Or acle p r ocess is inv oked, on behalf of t he end user, and w e hav e t h e en vir onm ent illu st r at ed in Figur e 2- 6 . Th e list ener is n o long er inv olved—it only serv ices t he est ablish ment of new in com ing connect ions. The " Back gr oun d Oracle pr ocesses" and t h e SGA, in Figur e 2- 5 , m ak e up t he pr ocessin g fr am ew ork of an op en dat abase—t h is w e call t he in st an ce. Th e dat af iles, w hich inclu de a v ariet y of Or acle files ser v ing diff erent pu rp oses, ar e w hat w e r ef er t o as " t he dat abase. " Your m anager could say, " Mak e a copy of t his dat ab ase and send it t o Calif orn ia." You w ould mak e copies of all t he d at afiles, send t h em t o Calif orn ia, and copy t h e files ont o a serv er w her e Or acle w as inst alled. Once t h at w as d one, y ou could " br ing u p" t his new inst an ce. The d iscussion su rr oun ding Figur es 2- 4 , 2- 5 , an d 2- 6 is design ed t o cry st allize wh at h appens du rin g a dat ab ase con nect ion . Ev en t h ough t h is is a chap t er on SQL* Plus, t he m ech anics of connect ing t o Oracle ar e t h e sam e f or any applicat ion—t he und er ly in g con nect ion pr ocess of a •. Net pr ogr am Table of acle, Content t o Or ors a JSP applicat ion usin g JDBC t o Or acle, is ident ical. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Ther e ar e v ariat ions By Kevin Owens

t o t h e ar ch it ect ur e j ust d escr ib ed . For exam ple, Oracle has an op er at ing env iron ment called Mult i- Th readed Ser v er ( MTS) w here u ser s shar e Or acle pr ocesses. I f y ou look at Figur e 2- 4 y ou m ight w onder ab out t he load on a ser v er once y ou ap pr oach h und reds of concur r enPrent t conn ect ions. Th e MTS env ir onm en t is an ar chit ect u r e opt im ized f or syst em s Pub lish er: ice Hall PTR ser vPub icinDat gm e: any Decemcon ber cu 0 5,rr2ent 003 end user s. I SBN: 0- 13 -0 850 33 -0

On ce y ou hav e laun ch ed SQL* Plus an d ar e conn ect ed t o a dat ab ase in st an ce, y ou can sub m it Pages: 44 8 SQL st at ement s for pr ocessin g. You can disconn ect , in w hich case y our point - t o- p oint dat ab ase con nect ion no longer ex ist s, an d fr om t his point you can t hen reconnect t o t he sam e dat ab ase, conn ect t o an ot her dat abase, or ex it t he SQL* Plus d esk t op applicat ion alt og et her. fect ively e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t [EfTeam LiBcreat ] Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.4 Disconnecting Ther e is a d iff er ence bet w een " disconnect ing fr om t h e dat ab ase" and ex it ing t h e SQL* Plu s app licat ion. When you use t h e EXI T com m and: 1 . Any d at abase chang es you subm it t ed, su ch as I NSERT st at em en t s, are com m it t ed; t hat is, t hey ar e per m anent ly app lied t o t he dat ab ase. Th is is because SQL* Plus does an im plicit comm it wh en y ou en d you r session . 2 . Your point - t o- p oint session is t er min at ed . •

Table of Content s

. am Finally, Plus sand pr ogr it sdure and y oud are ack Pr3 ogr m ing Oryaour cl e ®SQL* Tr i gger Storam e d Pex roce s, Thir Edi tibon

t o y our d esk t op or com man d

shell.

By Kevin Owens

From w it hin SQL* Plu s, you do hav e t he opt ion t o j ust D I SCONNECT fr om y our cu rr ent dat ab ase con nect ion bu t k eep t h e SQL* Plus app licat ion up . When you d isconnect : Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

d at es you subm it t ed, su ch as I NSERT st at em en t s, are com m it t ed; t hat 1 . Any I SBN: 0-abase 13 -0 850chang 33 -0 is, t hey ar e per m anent ly app lied t o t he dat ab ase. Pages: 44 8 2 . Your point - t o- p oint session is t er min at ed . 3 . You ar e st ill wit h in t h e SQL* Plus ap plicat ion bu t y ou no lon ger hav e a con nect ion t o a Ef fectdat ively e an age com abases acle! ems and dat abt ase ab creat ase. Fr omd tman h is point youplex can dat reconn ect twoitthh eOrsam e dSy atst abase, connect o a ex per t Kevindif Ow plor es PL/orSQL, acle's answ er wt oit h t h tehe Stex r uct ed mQuery ferens en tex dat abase, exit Or fr om SQL* Plus it ur com and. Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Whet h er y ou DI SCONNECT or you EXI T, SQL* Plus does an im p licit com m it . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of [ Team LiB ] Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.5 Command Line When y ou ar e t y pin g a SQL st at ement and need addit ional t ex t lin es, h it En t er/ Ret ur n. SQL* Plus w ill look at t he v ery last ( nonb lank ) char act er. I f t h at char act er is a sem icolon, t he SQL st at ement is pr ocessed; ot herw ise, SQL* Plus assum es you ar e st ill t y ping t he t ex t for a single SQL st at em en t an d n eed anot h er lin e. There is n o d ash or b ack slash needed t o cont inu e t y ping a SQL st at em ent on t o a nex t line. A SQL st at em ent en ds w it h a semicolon. Wh en y ou en d a line w it h a sem icolon, SQL* Plu s sen ds t h e SQL st at ement t o t he dat abase ser v er for p rocessing . The r esult s ar e sen t b ack an d display ed in y our SQL* Plus session. I f it is an UPDATE st at em en t or t he r esu lt set of t he •SELECT st at em Table s entof, Content t hese result s m ay includ e som e in for m at ion as t o how m any r ow s w er e Pr ogr am m ing Or a cl e ® Tr i gger s de P roce Thir d Edi up dat ed. I n t he follow in g exand amStor pleew seedure t hats, SQL* Plutisonackn owledg es t hat one r ow is up dat ed. Th is ver y sam e infor m at ion is available w it h in em bedded SQL w hen w e use: JDBC, By Kevin Owens ODBC, Net 8, or PL/ SQL. I n PL/ SQL w e can r efer en ce, f ollow in g an UPDATE, t he im plicit cur sor at t r ibut e SQL% ROWCOUNT t o det er m in e w hich r ow s w er e aff ect ed. SQL* Plu s pr ovid es aut om at ic shPTR ow ing t he n um ber of r ow s upd at ed . I n t he f ollow ing code, SQL* Plus Pub lish er:f eed Prentback ice Hall acknPub owDat ledg es t hat ow is u pdat ed. e: Decem ber one 0 5, 2r003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

SQL> UPDATE students SET college_major='Biology' Ef fect creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t 2 ively WHERE student_name='John'; Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 1 row updated. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of [ Team LiB ] Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.6 Changes on the Command Line The CHANGE com m and is v er y sim ple and of t en sim pler and less t im e- con sum in g t han using a m ou se cu t - and- p ast e. The act ual com m and is CHANGE bu t can be ab br ev iat ed wit h t h e char act er " C. " Any t ex t ed it or ch ange com m and r eq uir es a f ield t er m inat or and, in t h is case, t he t er m inat ing char act er is a f orw ar d slash—b y defau lt it is a f orw ar d slash bu t any ch aract er can be u sed, as w e w ill illust r at e. The CHANGE com m and sy nt ax is:



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

C[HANGE]/old_text/new_text[/] Pub lish er: Prent ice Hall PTR

Use t he f ollow ing t o just r em ov e t ext : Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

C[HANGE]/old_text Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d It eaches n t his and sequ en tn sect t able is d used o dem onst r at e SQL* Plus. A yousub w hat y ou eed ion t o s, kn a owSTUDENTS t o build rob ust an comt plex dat ab ases f or y our b usiness. STUDENTS t able can b e creat ed using t he SQL p rov ided in Ch apt er 1, Sect ion 1. 6 , " Behind Tables." Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our A h ab elpases ful SQL* Plu spor comm an siness d is t her ules DESCRI BEar com m andt o( DESC) , wand h ichmdescr a t able. dat t o incor at e bu w hich e easy man age odif yibes as t he The D ESCRI BE com man d, f irst of all, is a qu ick way t o see if a t able ex ist s. You g et a bu sin ess evolv es. Topics cov er ed include: har m less er r or if you at t em pt t o d escrib e a n onexist ent t able. I f t he t ab le does ex ist , t h e com man d d isp lay s each colum n nam e, colum n t yp e, plus a " Null" in dicat or t o t ell y ou if t he columView n is in a gmconst andatr ory dat or colum n con st r aint s are discu ssed in Ch apt er 3. aint colum s in t hn—man e dat a dict iony ar y The f ollow in g session t ext st ar t s w it h a DESCRI BE com m and and f ollow s w it h som e I NSERT Com Plus plex CHANGE r ule enf orcem t and SQL* com menands. Edit or ial comm ent s are in it alics and und er lined. Each un derlined comm ent pr ecedes w hat t hat com ment is descr ibing . PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SQL> desc students I nt er - pr ocess com mu nicat ions Name Null? Type Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch --------------------- -------- -----------m or e STUDENT_ID VARCHAR2(10) STUDENT_NAME Pr ogr am m ing Oracle Tr igger s and St orVARCHAR2(30) ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce COLLEGE_MAJOR VARCHAR2(20) for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly STATUS VARCHAR2(20) int ellig en t , com plex dat abases. Select table row count . [ Team LiB ] SQL> SELECT COUNT (*) FROM students;

COUNT(*) [ Team LiB ] ---------0 Insert a row. SQL> INSERT INTO students VALUES 2 ('A101', 'John', 'Biology', 'Degree'); 1 row created.

We j ust in ser t ed on e r ow for t he st ud en t Joh n. We can t y pe an ot her I NSERT st at em ent , but for t his ex er cise, w e'll CHANGE t he SQL st at em en t in t he SQL* Plu s buf fer . Wh en w e com plet e our CHANGE, w e will LI ST t he con t en t s of t he SQL* Plu s buf fer an d ex ecu t e ( using t he for w ard slash ) t h e SQL st at em ent . •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Change STUDENT_ID. Pub lish er: Prent ice Hall PTR

SQL> Pubc/101/102/ Dat e: Decem ber 0 5, 2 003 2* ('A102', 'John', 'Biology', 'Degree') I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Change "John" to "Mary". SQL> c/John/Mary 2* ('A102', 'Mary', 'Biology', 'Degree') Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d For field use t o"." Change major. t eaches you separator w hat y ou n eed kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. SQL> Using c.Biology.Math/Science. easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 'Mary', adv2* ant('A102', ag e of Or acle feat ur 'Math/Science', es such as t rig gers 'Degree') and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he LIST SQL*Plus (lower case L). bu sin ess evolv es.buffer Topics cov er ed include: SQL> l in g const s in t h e values dat a dict ion ar y 1 View insert intor aint students 2* ('A102', 'Mary', 'Math/Science', 'Degree') Com plex r ule enf orcem en t Execute statement, then select all rows. PL/ SQL p r ogr am un it s and langu age f eat u res SQL> / Dat a t y pes and comp osit e st r u ct u re 1 row created. Er r or han dling and except ions SQL> SELECT * FROM students; I nt er - pr ocess com mu nicat ions STUDENT_ID STUDENT_NA COLLEGE_MAJOR STATUS ---------Declar at---------iv e const r aint-------------------s, including p rim ar y k ey , -----u nique, f or eign k ey, ch eck , and m uch A101 m or e John Biology Degree A102 Mary Math/Science Degree Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce SQL> for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiBPlus ] session int r odu ces a few t op ics in ad dit ion t o t he basic CHANGE comm and . This SQL* SQL* Plus m aint ains a local edit b uf fer —big en ough only f or a sing le SQL st at em ent . SQL* Plus k eep s t he last SQL st at em ent you t y ped in it s local edit m em or y bu ff er .

[ Team LiB ] I f you m ist yp e a SQL st at em en t , t h at m ist yp ed st at em en t is in y our local bu ff er and you can ch ange w h at y ou t yp ed b ecause y ou are ed it in g t he cont ent s of t hat buf fer . You can alw ay s execut e t h e cur rent SQL st at em en t by t yp ing t he f or war d slash . You can alw ay s LI ST t he cont ent s of t he edit buf fer w it h t he LI ST ( abb rev iat ed w it h t he let t er " L" ) com m and . A com m on t yp ing er r or is t o t r anspose t he " R" an d " F" ( t hey ar e adj acen t on t he key boar d) w hen t yp ing t he " FROM" k eyw or d of a SELECT st at ement . For ex am ple,

* FORM students; •SQL> SELECT Table of Content s SELECT Pr ogr am m*ingFORM Or a cl estudents ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on * By Kevin Owens ERROR at line 1: ORA-00923: FROM keyword not found where expected Pub lish er: Prent ice Hall PTR

Make correction. We do not need a forward slash at the end. Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

SQL> c/FORM/FROM Pages: 44 8 * FROM students 1* SELECT SQL> / Ef fect ively creat e an d man COLLEGE_MAJOR age com plex dat abases wSTATUS it h Or acle! Sy st ems and dat ab ase ex per t STUDENT_ID STUDENT_NA Kevin Ow ens ---------ex plor es PL/ SQL, Or acle's answ er t o t h-----e St r uct ur ed Query Langu age ( SQL) , an d ----------------------------t eaches you wJohn hat y ou n eedBiology t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. A101 Degree A102 Mary Math/Science Degree Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases in t og incor por at bu siness w hichPlu arse edit easy man age m odif y as he. The f ollow is a sum meary of com rmules on SQL* ingt ocomm and and s discussed so tfar bu sin ess evolv es. Topics cov er ed include: The ch ange com m and is CHANGE bu t y ou can j ust u se t he single char act er " C. " View in g const r aint s in t h e dat a dict ion ar y Forw ar d slash is t he default field separ at or b ut you can use any char act er—t he Comem plex enfex orcem en t used a period because a f or w ard slash is a ch ar act er w it hin afor en rt ule ioned am ples t he t ex t being ch anged. PL/ SQL p r ogr am un it s and langu age f eat u res You can leav e off t h e en ding for w ar d slash follow ing t he n ew - t ex t f ield —sh ow n in t he Dat a t y pes comp st rple. u ct u re im mediat elyand pr eced inosit g exeam Er r orcan hanalw dling except ionsyou j ust t y ped or w hat you j ust ex ecut ed —t hat SQL You ay sand chang e w hat st at ement is in t he SQL* Plus buf fer f or you t o edit or resubm it . I nt er - pr ocess com mu nicat ions You can LI ST t he cu rr ent SQL st at em ent w it h t h e LI ST ( just use t he let t er " L" ) Declar at iv com man d.e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e You can alw ay s r un w hat ever y ou ar e ed it ing w it h t h e for w ar d slash. This has n ot hing t o Pr ogr do am m Tr igger s and St or ed for Pr w oced es , Th Ed it ion aluable esou w iting h t Oracle he chang e comm an d. The ardurslash is iradcomm an, disuan nt oinv it self t hat rm eanrce s: for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Ex ecu t e t he last SQL st at em ent or w hat ev er is in t h e SQL* Plus b uff er . int ellig en t , com plex dat abases. Tw o f or t hcom in g point s on t h e CHANGE comm and : [ Team LiB ] You can u se CHANGE t o r emov e t ex t w it h in a SQL* Plu s st at ement .

When [ Team LiB ]t y ping a m u lt iline SQL st at em ent , y ou can CHANGE any line b ut y ou m ust f irst set y our " cur r ent line" t o t h e line being chang ed . You r em ov e t ext by n ot t y pin g a NEW_ TEXT clause. Fir st , t h e CHANGE com man d d ef init ion w it h t his considerat ion ( n ot ice NEW_TEXT is w holly in br ack et s) m ak es it opt ion al.

C[HANGE]/old_text[/new_text[/]]

Becau se t he ent ir e NEW_ TEXT clause is op t ional, t he OLD_ TEXT is rem oved w hen t her e is no NEW_ TEXT. For ex amp le: •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

SQL> SELECT student_id, student_name FROM students; Pub lish er: Prent ice Hall PTR

STUDENT_ID STUDENT_NAME Pub Dat e: Decem ber 0 5, 2 003 ---------- -----------I SBN: 0- 13 -0 850 33 -0 A101 John 8 A102 Pages: 44Mary Use change command to drop "student_id," then execute. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t SQL> c/student_id, Kevin Ow ens ex student_name plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 1* select from students tSQL> eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. / Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake STUDENT_NAME adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our -----------dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he John bu sin ess evolv es. Topics cov er ed include: Mary View in g const r aint s in t h e dat a dict ion ar y CHANGE can be used t o r emov e ad dit ional char act ers w hen w e m ist y pe. The f ollow in g r em ovCom es an ex rt rule a com m a. en t plex enf orcem PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re We have extra comma after Er r oranhan dling and except ions"student_name." SQL> I SELECT nt er - pr ocess student_name, com mu nicat FROM ions students; SELECT student_name, FROM students Declar at iv e const r aint * s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch or e line 1: ERRORm at ORA-00936: missing expression Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for datthe abase d ev elopers,and d esign er s, andthe pr ojquery. ect leader s look in g t o b uild an d m aint ain t r uly Make correction resubmit int ellig en t , com plex dat abases. SQL> c/, [ Team LiB ] 1* select student_name from students SQL> / STUDENT_NAME

-------------------[ Team LiB ] John Mary

Mu lt iline edit in g is accom plish ed b y fir st ident if yin g t h e line nu m ber you int en d t o edit . The CREATE TABLE com m and , in t he b eg in ning of Sect ion 1. 8, is a CREATE TABLE st at ement t hat w as t y ped using fiv e lines. Ent er ing car r iage r et ur ns as we t yp e is don e t o m ak e it easier t o r ead t h e st at em ent w e ar e t y ping. Lengt hy , m ult ilin e SQL st at ement s can easily b e saved in a SQL scr ipt file f or lat er use. I f you 'r e com for t able w it h SQL and y ou t yp e w ell, y ou m ay oft en fin d t he need t o t y pe a len gt hy SQL st at em ent t o q uickly g et t o som e inf orm at ion t hat is of im mediat e need ; in ot her w or ds, y ou' re in a big hur r y. The f ollow ing ex amp le is a scen ario of corr ect ing a m ult iline SQL st at em en t ag ainst a dat a dict ion ary view .



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens "column_type" should be "data_type," we expect an error.

SQL> SELECT column_name, column_type lish er: Prent ice Hall PTR 2PubFROM user_tab_columns 3PubWHERE table_name='STUDENTS'; Dat e: Decem ber 0 5, 2 003 SELECTI SBN: column_name, 0- 13 -0 850 33 -0 column_type * Pages: 44 8 ERROR at line 1: ORA-00904: invalid column name Ef e an1d. 8,man dat abases h ionar Or acle! abion aseabout ex per t Chfect aptively er 1, creat Sect ion int rage oducom ced plex t he Or acle d at a wditict y t hSy at st stems or esand infordat m at Ow ens plore. esI tPL/ SQL, acle's answ er tof o tinf h eorm St r at uct ur ed Queryt ables, Langu age tKevin he t ables w e ex creat also st orOres a g reat deal ion besides su ch( SQL) as , an d t eaches you w hat n eed t o kn ow t oeat build ust an d com plexENTS. dat ab We asescan f or qu y our pr iv ileges t h at u sery souhav e. We hav e cr ed arob t able called STUD er y bt usiness. h e dat a dict ionar y v iew USER_TAB_COLUMNS, as in Sect ion 1. 8 , t o see w hat colu m ns ar e defin ed in Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake t he dat a dict ion ary . adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases e at buem siness w Plus hich alw ar e ay easy t o man m odif y ber as tphe Ty ping a mtuoltincor iline por SQLatst ent inr ules SQL* s display s aage n exand t - line num rom pt . bu sin ess evolv es. Topics cov er ed include: Ear lier , SQL* Plu s displayed t he " 2" b ef or e " FROM, " and display ed " 3" befor e " W HERE. " The af or em ent ioned SQL st at ement needs a cor r ect ion . We m ade a m ist ak e w it h View in g const r aint s in t h e dat a dict ion ar y COLUMN_TYPE. We should hav e check ed t he def in it ion of t h e v iew USER_TAB_COLUMNS w it h a D ESCRI man I f w eendo Com BE plexcom r ule enfd. orcem t t his n ow w e see t hat t he colum n is not COLUMN_ TYPE b ut DATA_TYPE. PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SQL> desc user_tab_columns NameI nt er - pr ocess com mu nicat ions Null? Type -------------- -------------- -------- ------------Declar at iv e const r aint s, including p rim ar y kVARCHAR2(30) ey , u nique, f or eign k ey, ch eck , and m uch TABLE_NAME NOT NULL m or e COLUMN_NAME NOT NULL VARCHAR2(30) DATA_TYPE VARCHAR2(106) Pretc ogr am igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce . m . ing . .Oracle . . .Tr . for dat abase d ev elopers, d esign er s, and pr oj ect VARCHAR2(3) leader s look in g t o b uild an d m aint ain t r uly USER_STATS int ellig en t , com plex dat abases. AVG_COL_LEN NUMBER [ Team LiB ] The SQL st at em ent is st ill in t h e SQL* Plu s bu ff er . Go t o t he f ir st lin e—t h at is w h er e t h e err or is—and CHANGE t he t ex t . At t he SQL* Plu s pr om pt , w e t yp e t he char act er for t he n um er al " 1. " SQL* Plu s r espon ds w it h t he t ex t fr om t h e fir st line.

[ Team LiB ]

The text typed is the numeral one, not letter "L." SQL> 1 1* SELECT column_name, column_type Change command to make correction. SQL> c/column_type/data_type 1* select column_name, data_type List SQL*Plus buffer, then execute the SQL statement. •

Table of Content s

SQL> Pr ogr am lm ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, 1 SELECT By Kevin Owens column_name, data_type 2 FROM user_tab_columns 3* WHERE table_name='STUDENTS' SQL> Pub/ lish er: Prent ice Hall PTR

Thir d Edi ti on

Pub Dat e: Decem ber 0 5, 2 003

COLUMN_NAME DATA_TYPE I SBN: 0- 13 -0 850 33 -0 ------------------------------ --------Pages: 44 8 STUDENT_ID VARCHAR2 STUDENT_NAME VARCHAR2 COLLEGE_MAJOR VARCHAR2 STATUS VARCHAR2 Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches yout inser w hatt ing y ou addit n eedional t o knlin ow comwplex ablier ases or ytour What abou est oofbuild t ex t ?rob Forust ex an amdple, e seedat ear , f rfom he b usiness. DESCRI BE on USER_TAB_COLUMNS, t her e is a colum n called AVG_COL_ LEN. Th is looks Using easyo- follow inst r uctyions d ex t his book pr Use esent ues o t ake ( ju st int er est ing . tMod if y t he quer t o inan clud e tam hisples, colum n as w ell. t hset echniq SQL* Plu s ItNSERT adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat allow y our use t h e fir st char act er " I " ) com m and. W e w ant t o insert our addit ional t ext aft er line 1 . We dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he can accom plish t h is by t y pin g a one ( " 1 " ) , t h en " I " follow ed by t he new t ex t —t h e change is bu sinplet esse.evolv es. Topics cov er ed include: com View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t Type LIST (L) command. PL/ SQL p r ogr am un it s and langu age f eat u res SQL> Dat l a t y pes and comp osit e st r u ct u re 1 SELECT column_name, data_type 2 Er FROM user_tab_columns r or han dling and except ions 3* WHERE table_name='STUDENTS' I nt er - pr ocess com mu nicat ions Type numeral one. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch SQL> m1or e 1* SELECT column_name, data_type Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly INSERT ("I"), new text. int ellig en t , com plex dat abases. SQL> i ,avg_col_len [ Team LiB ] Type LIST (L) command then execute with "/". SQL> l

1 SELECT [ Team LiB ] column_name, data_type 2 ,avg_col_len 3 FROM user_tab_columns 4* WHERE table_name='STUDENTS' SQL> / COLUMN_NAME -----------------------------STUDENT_ID STUDENT_NAME COLLEGE_MAJOR STATUS

DATA_TYPE AVG_COL_LEN ---------- ----------VARCHAR2 4 VARCHAR2 4 VARCHAR2 10 VARCHAR2 6

SQL> •

Table of Content s

Does y our q uery sh ow no num b er s u nder t h e AVG_COL_LEN? Th is colu m n show s t he av er age Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on colum n leng t h and is a v it al st at ist ic t hat is used b y t he Or acle Cost Based Op t imizer . I f you By Kevin hav e noOwens st at ist ics, y ou can gener at e t h e st at ist ics f or y our STUDENTS t able w it h t he f ollow in g com man d an d rer un y our qu er y —t his t im e y ou' ll see t he st at ist ics. One m et hod for gat her ing st at ist ics on t h e STUD ENTS t ab le is w it h t he analy ze com man d ( t he PL/ SQL packag e, Pub lish er: Prentis iceaHall PTR DBMS_ STATS, m or e r obust for m of g at herin g st at ist ics but ANALYZE, in t his case, is a PubhtDat e: Decem ber 0t5, 2 003 st r aig f orw ar d solu ion. ) I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

SQL> ANALYZE TABLE students COMPUTE STATISTICS; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d Table Ow analyzed. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. SQL> Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he Now r un t h e afor ement ion ed q uery an d see v alues in t he AVG_ COL_ LEN colu m n. bu sin ess evolv es. Topics cov er ed include: We ad ded on e line of t ext and inser t ed t h e t ext bet w een lines 1 and 2. Su ppose y ou w ant t o add sever al lines. For t his j ust t h e I NSERT ( " I " ) com man d an d t hen Ent er / Ret ur n—t here is n o View in g const r aint s in t h e dat a dict ion ar y add it ion al t ex t . You ar e t hen in a for m of " inp ut mod e. " You can t y pe as man y add it ion al lines as y ou lik e. Ty ping En torcem er / Reten u rn Com plex r ule enf t t w ice t ak es you out of " inp ut m od e. " I n gener al, w hen you hav e m ult iple lines t o chang e or add , y ou sav e t im e w hen you save t he SQL st at em en t t o a scr ipt PL/ file, editp rtogr hatam file,unand r un langu it f romage SQL* s. SQL it s and f eatPlu u res FollowDat inga ar t w oand final t opics edit t yepes comp ositabout e st r u ct u reing in SQL* Plu s. Er r or han dling and except ions Delet in g a line— not t o of t en u sed, but w e' ll cover it her e. I nt er - pr ocess com mu nicat ions App en ding t ext t o a line— a v er y u sef ul SQL* Plus com m and. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch DEL ismtor hee com man d t o delet e a line. Th e pr evious SQL* Plu s scenar io in ser t ed , af t er lin e 1, t he t ex t : " , AVG_ COL_ LEN. " This becam e Line 2 . Sup pose w e now wan t t o delet e t his line. Set t ham e cur rentOracle line atTr2, t h en t y peStDEL. Pr ogr m ing igger s and or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] Type LIST (L) command.

SQL> [ Teaml LiB ] 1 SELECT column_name, data_type 2 ,avg_col_len 3 FROM user_tab_columns 4* WHERE table_name='STUDENTS' Go to line 2. SQL> 2 2* ,avg_col_len Delete this line. SQL> del Type LIST (L) • Table showing of Content sdeletion. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

SQL> l By Kevin Owens 1 SELECT column_name, data_type 2 FROM user_tab_columns 3* WHERE table_name='STUDENTS' Pub lish er: Prent ice Hall PTR SQL> Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

When Pages: y ou set 44 8a " cur r en t line" b y t y ping a n um eral follow ed by en t er / r et ur n, t he t ex t of t h at line is r efr esh ed by SQL* Plu s. You can t hen edit t h at line w it h a CHANGE or APPEND com man d. Wh en y ou LI ST t h e SQL* Plus bu ff er , t h e " cur r en t line" is alw ay s r eset t o t h e last line. So a LI ST f ollowed by a CHANGE com man d w ill alw ay s at t em pt t o ap ply y our chang e t o tEf he last lin ecreat of t he SQL* Pluage s buf fer .plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t fect ively e an d man com Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d The APPEND v ert oy kn usefu et im y ou pe aplex SELECT stases at emfent t henb usiness. y ou t eaches you wcom hatmy and ou n is eed ow l.t oSom build robes ust an tdy com dat ab or y; our w ant t o q ualify it by ap pending a WHERE clause. The f ollow ing qu er y , as f irst w rit t en , select s colum neasyn amt es f r om tinst he USER_TAB_COLUMNS. Using o- follow r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SQL> View SELECT table_name, in g const r aint s in t hcolumn_name e dat a dict ion ar y 2 FROM user_tab_columns; Com plex r ule enf orcem en t TABLE_NAME COLUMN_NAME PL/ SQL p r ogr am un it s and langu age f eat u res ----------------------------------STUDENTS STUDENT_ID Dat a t y pes and comp osit e STUDENT_NAME st r u ct u re STUDENTS STUDENTS COLLEGE_MAJOR Er r or han dling and except ions STUDENTS STATUS I nt er - pr ocess com mu nicat ions Let ' s m odify t his t o see j ust t h ose colum n s t hat ar e of t yp e VARCHAR2. We sim ply use t h e Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch APPEND comm an d ( ab br eviat e w it h " AP" ) t o ap pend a WHERE clause. m or e We ar e ap pending t ex t t o t he clause: " FROM USER_ TAB_COLUMNS. " This r equir es a space Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce plus an ap pended WHERE clause. The ap pend comm and , w hich is " AP, " is separ at ed f rom t he for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly app en ded t ex t wit h a sp ace. You need t w o spaces—t he second space is t h e fir st char act er of int ellig en t , com plex dat abases. t he t ex t you ar e app en ding . The ap pend com m and is: [ Team LiB ]

Two spaces [ Team LiB ] after "ap", then submit SQL query. SQL> ap where data_type = 'VARCHAR2' 2* FROM user_tab_columns where data_type='VARCHAR2' SQL> / TABLE_NAME -----------------------------STUDENTS STUDENTS STUDENTS STUDENTS



COLUMN_NAME ------------STUDENT_ID STUDENT_NAME COLLEGE_MAJOR STATUS

You can ap pend t o an y line. Just t yp e t he line num ber as show n w it h t he CHANGE Table of Content s com man d an d t hen d o an APPEND .

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

I gnor e the By Kevin Owens

sem icolon w h en y ou ap pend t ext t o t he last line. Wh en y ou t y pe a SQL st at ement y ou alw ay s end w it h a sem icolon. Th en , w hen you LI ST t he SQL* Plus b uf fer, y ou see t her e is no sem icolon. Wh en edit ing w it h eit h er t he CHANGE or APPEND Pub lish er: Prent icet Hall com man ds, hin kPTR about t he fact t h at y ou ar e ed it ing t he cont ent s of t he SQL* Plus buDat ff er w h ich not include t he semicolon. Pub e: ,Decem berdoes 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

The af or em ent ioned exam ple ap pended a WHERE clau se and w e had t o b eg in w it h a sp ace t o Pages: 44 8 det ach t he t ex t w it h a space. You can som et imes j ust leav e off a ch ar act er w hen t y ping —in w hich case y ou sim ply ap pend ch ar act er s t o t he end of a line. Th e follow ing st at ement , as fir st ent er ed, is m issin g t h e " S" fr om t he STUDENTS t ab le—som et im es w e j ust cann ot r em em ber if a t ab le nam e is singu lar or plur al. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv antoff ag e the of Or"s". acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Left dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv * es.FROM Topics cov er ed include: SQL> SELECT student; SELECT * FROM student * View in g const r aint s in t h e dat a dict ion ar y ERROR at line 1: ORA-00942: ororcem viewendoes not exist Com plextable r ule enf t "ap""s" PL/ SQL p r ogr am un it s and langu age f eat u res SQL> Dat ap ast y pes and comp osit e st r u ct u re 1* SELECT * FROM STUDENTS SQL> Er / r or han dling and except ions I nt er - pr ocess comCOLLEGE_MAJOR mu nicat ions STUDENT_ID STUDENT ---------- ------- -------------------iv e const rBiology aint s, including p rim ar y A101 Declar atJohn m or e A102 Mary Math/Science

STATUS -----kDegree ey , u nique, f or eign k ey, ch eck , and m uch Degree

Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce SQL> for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. You can ent er a SQL st at ement int o t he SQL* Plus buf fer w it hou t execut ing it , t hen list it , t hen [ Team LiB ] execut e it . This is not t he nor mal sequ en ce of ev ent s, bu t is som et imes u sed as a t echn iq ue w it hin SQL* Plus scr ipt s w here it is desirab le t o h ave t he scr ipt list ed, in a spool f ile, an d t hen for ce t h e ex ecu t ion of t hat st at em ent ; t hat is, list fir st , t hen ex ecu t e. You do t his by n ot ent er in g a sem icolon an d t yp in g ENTER t w ice—t h is ef fect ively ends t he " inp ut " m ode. Not ice

t[ he follow in ]g has no sem icolon at t he en d of line on e. Team LiB

Type statement, ENTER, LIST (L), then submit query (/).

SQL> 2 SQL> 1* SQL>

SELECT * FROM students l SELECT * FROM STUDENTS /

STUDENT_ID STUDENT COLLEGE_MAJOR STATUS • Table of Content s ---------- ------- -------------------- -----Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on A101 John Biology Degree By Kevin Owens Mary A102 Math/Science Degree

er: PrentSQL* ice Hall PTR session en t er s a SQL st at ement w it hout a final sem icolon. When you ThePub p r lish eceding Plus e: st Decem ber/ r0et 5, u2 r003 t y pePub t h Dat e fir ent er n, SQL* Plus r espond s w it h a pr om pt for a second line of SQL t ex t . SQL* Plus int0-er s 33 t he I SBN: 13pr -0et 850 -0 second ent er/ ret ur n as " w e'r e d one" and r et ur ns t he SQL* Plus pr om pt . The44SQL st at em en t is ent er ed int o t he SQL* Plu s buf fer b ut not ex ecu t ed . We can list Pages: 8 t he buf fer and t h en ex ecut e it . This scen ario can be im p lem ent ed in a SQL* Plu s scr ipt by hav ing a SQL st at em ent wit h out a sem icolon f ollow ed by a blank lin e follow ed b y a LI ST, t hen a f or w ard slash ex ecut e com m and .

Ef ivelyarcreat e an Plus d man age plex wul it hedit Or ing acle!com Sy st Tofect su mm ize SQL* edit ingcom , t he t wodat m abases ost helpf mems andsand ar e:dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. CHANGE ("C") Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of ("AP") Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our APPEND dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he We h ave also look ed at cov er ed include: bu sin ess evolv es. Topics LIST View in("L") g const r aint s in t h e dat a dict ion ar y INPUT ("I") Com plex r ule enf orcem en t DELETE PL/ SQL p("DEL") r ogr am un it s and langu age f eat u res Finally, Datt o a execut t y pes and e t hecomp SQLosit st at e em st r en u ctt ut re h at is cur r en t ly in you r SQL* Plu s bu ff er , y ou t y pe a for w ar d slash ( " / " ) . One v ar iat ion on t he for w ard slash is t he RUN com m and. The RUN Er r or except com man d fhan ir st dling list s t and he cont ent sions of t he SQL* Plus b uf fer and t h en execut es t h e st at em ent . I t is ident ical t o t he sequence: LI ST follow ed b y a f or w ard slash . I nt er - pr ocess com mu nicat ions Declar [ Team LiB ]at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.7 Scripts You can alw ay s save t he cont ent s of t he SQL* Plus b uff er t o a file f or r eu se—j ust t yp e t he SAVE com m and and a filenam e. I f t h e file alr eady exist s, SQL* Plus t ells y ou. You can do a " SAVE filenam e REPLACE, " w hich w ill r eplace t he cont ent s of an ex ist in g file. You also h ave t he opt ion t o d o a " SAVE f ilenam e APPEND, " w hich adds you r SQL* Plus bu ff er st at em ent t o t he en d of t h e filenam e specif ied . Wher e does t h e saved file go? I n UNI X t h e sav e f ile goes int o t he d ir ect ory fr om w hich you launch ed SQL* Plus. I n Window s, it goes t o t h e Or acle " bin" dir ect or y , bu t , if you set u p a shor t cut and ch anged t he st ar t - in dir ect or y , as r ecom m ended in Sect ion 2. 1 , t h e file is sav ed •t o a dedicat ed Table of Content s direct or y. The f ollow ing illust r at es how w e sav e a select st at em ent int o a scr ipt Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on file. By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

SQL> SELECT * FROM students; I SBN: 0- 13 -0 850 33 -0

Pages: 44STUDENT 8 STUDENT_ID COLLEGE_MAJOR STATUS ---------- ------- -------------------- -----A101 John Biology Degree A102 Mary Math/Science Degree Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ensstudents_select ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d SQL> save t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Created file students_select SQL> Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o save incorapor e bu siness r ules hich e. ar e easy t o man age and m odif y as t he We can also scratipt using a f ull p atwhnam bu sin ess evolv es. Topics cov er ed include:

View in g const r aint s in t h e dat a dict ion ar y plex r ule enf orcem en t SQL> Com save D:\sqlplus_scripts\students\students_select Created file D:\sqlplus_scripts\students\students_select PL/ SQL p r ogr am un it s and langu age f eat u res SQL> Dat a t y pes and comp osit e st r u ct u re The f ile ension of and a SQL* Plusions sav ed f ile is alw ay s " . SQL." Er rex or t han dling except The f ile ext ill be com identmu ical to w hat you t y pe dur ing y our session—it is t he ex act t ex t f rom I ntter - prwocess nicat ions t he SQL* Plu s buf fer . The sem icolon is dr opp ed an d a for w ar d slash is added as a last and fin al line in at t he ed frile. st rat e, pt yrim peara yselect at em en t ,eign b ut dk ey, o n ot y pe, and a sem Declar iv esav const aintTo s, illu including k ey , ustnique, f or chteck micolon. uch Then m t yor pee f orw ar d slash t o ex ecu t e t he SQL* Plus buf fer . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. SQL> [ TeamSELECT LiB ] * FROM students 2 / STUDENT_ID STUDENT COLLEGE_MAJOR

STATUS

---------[ Team LiB ] ------- -------------------- -----A101 John Biology Degree A102 Mary Math/Science Degree SQL>

The af or em ent ioned is ident ical t o t y ping " SELECT * FROM st ud en t s" an d ad ding a sem icolon. Eit h er way , t h e act ual t ex t in a scr ipt file, fr om a SAVE com m and, w ill be t w o lines: t he select st at ement m inus t he semicolon and a secon d line wit h a for w ar d slash.

SELECT * FROM students • Table of Content s /

".SQL" file line 1 ".SQL" file line 2

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

The t hr ee opt ions w it h t he SQL* Plu s SAVE com m and ar e: Pub lish er: Prent ice Hall PTR

SAVE Pub Dat e:filename Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

SAVEfilename REPLACE Pages: 44 8

SAVEfilename APPEND You ex ecut e a SQL scr ipt fr om SQL* Plus w it h t he sy nt ax : @filenam e. For ex am ple: Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake SQL> adv ant@students_select ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he STUDENT_ID STUDENT COLLEGE_MAJOR STATUS bu sin ess evolv es. Topics cov er ed include: ---------- ------- -------------------- -----A101 John Biology Degree const r aintMath/Science s in t h e dat a dict ion ar y Degree A102 View in g Mary SQL> Com plex r ule enf orcem en t PL/dSQL p rm ogr un it sPlus and scrip langu eat u res Du ring ev elop enam t , SQL* t sage ar e fused t o dr op and r ecr eat e all t he t ables of an app licat ion. Also for d ev elopm en t , scr ipt s are used t o load t est dat a. Scr ipt s can be Dat a t y pes and comp osit e st r u ct u re emb ed ded wit h in UNI X Kor n Shell scr ipt s t o per for m d aily Oracle b ack up s. They are used f or ad hoc ouhan bleshoot g, (except i. e., t oions show ex ist ing lock s on dat ab ase object s, t o sh ow Er trror dling in and per for m ance of m em or y usag e, an d man y ot her d at abase m et r ics) . I nt er - pr ocess com mu nicat ions You can cr eat e a SQL scrip t f rom SQL* Plu s w it h a SAVE comm and , bu t scrip t s of len gt h ar e usually cr eatated it h a rhost edincluding it or. The cont SQL scrip t can m ore SQL Declar iv ewconst aint s, p riment ar ys kof eya, u nique, f or eign ink clu ey,de chone eck , or and m uch st at ement s, plus SQL* Plus com m ands. You can com m ent w it hin a SQL* Plus scrip t w it h a m or e dou ble dash. The f ollow ing is a SQL* Plu s scr ipt t hat cont ains t w o SQL SELECT st at em ent s plus w o mcom lines—t hes fand ile isStfiv es. Pr ogrtam ing ment Oracle Tr igger oreedlinPr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] -- Filename: SELECT_STUDENTS.SQL -- Script to select STUDENTS data.

SELECT student_name, college_major FROM students; [ Team LiB ] SELECT student_id, student_name, college_major FROM students WHERE status = 'Degree';

The af or em ent ioned scr ipt w ould ex ecut e f rom SQL* Plu s w it h:

SQL> @select_students

SQL* Plus scrip t s can cont ain SQL* Plus com m ands. Th is includes SQL* Plus f or mat t in g com man ds. A com m on SQL* Plu s com m and of t en em bedded in a SQL* Plus scrip t is t h e •COLUMN com Table s manofd.Content Th e SQL* Plus COLUMN com man d is used t o rest r ict t he num ber of Pr ogr am m ing Or a cl e ® Tr i gger s andn,Stor e d Pin roce dure s, Thir d pu Edittias on w ell as d esign at e a specific char act er s, f or a single colum used t he SQL out heading . By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

-- Filename: SELECT_STUDENTS.SQL Pages: 44 8 -- Script to select STUDENTS data. COLUMN college_major FORMAT A12 HEADING 'College|Major' COLUMN student_name FORMAT A7 HEADING 'Student|Name' COLUMN student_id FORMAT A7 HEADING 'Student|ID' Ef fect ively creat e an d mancollege_major age com plex datFROM abases w it h Or acle! Sy st ems and dat ab ase ex per t SELECT student_name, students; Kevin Owstudent_id, ens ex plor es PL/ SQL, Or acle's college_major answ er t o t h e St rFROM uct ur ed Query Langu age ( SQL) , an d SELECT student_name, STUDENTS tWHERE eachesstatus you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. = 'Degree'; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake SQL> @select_students adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab asesStudent t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he Student College bu sin ess evolv es. Topics ID Name Majorcov er ed include: ------- ------- -----------A101 John Biology View in g const r aint s in t h e dat a dict ion ar y A102 Mary Math/Science Com plex r ule enf orcem en t A SQLPL/ st SQL at empent s ends w itlangu h a sem A SQL* Plus com m and does n ot n eed t o end r ogralw amayun it s and ageicolon f eat u.res w it h a semicolon. Th e next sect ion illu st rat es ot her SQL* Plu s com man ds: HEAD I NG, PAGESI ZE, andcomp FEED BACK. Dat a t yTERM, pes and osit e st r u ct u re Er r or han dling and except ions [ Team LiB ] I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.8 Script Output You r ed ir ect SQL* Plus ou t put w it h a SPOOL com m and. You ch oose t o " spool t o a file" at t he beginn ing of t he scr ip t . You " end t he spooling p rocess" at t h e end of t he scrip t . Som e scr ipt s can be lengt h y—t hey dr op and recr eat e 50 t ables and include m an y inser t st at em ent s f or t est dat a. These t yp es of scr ipt s of t en spool out pu t f or v er if icat ion pur p oses.

•-- filename Table of Content s MY_STUDENTS.sql Pr ogr am my_students m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on spool DROP TABLE By Kevin Owens students; CREATE TABLE students (student_id VARCHAR2(10), student_name Pub lish er: Prent ice VARCHAR2(30), Hall PTR college_major VARCHAR2(15), Pub Dat e: Decem ber 0 5, 2 003 status VARCHAR2(20) ) TABLESPACE student_data; I SBN: 0- 13 -0 850 33 -0

Pages: 44 8

INSERT INTO students VALUES ('A123','John','Math','Degree'); INSERT INTO students VALUES Ef('A124','Mary','Biology','Degree'); fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d COMMIT; tspool eachesoff you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv Or acle feat ur es as ed t rigMY_STUDENTS. gers and st oredLST. pr oced ur esf eaton u rlyest he t hat allow The ant ou tag puet of f rom t he spool filesuch is nam I t cont ains f eedb acky our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he fr om SQL* Plu s. The t ex t of t h e sp ool out p ut file is br ief and pr imar ily show s t h at t h e bu sin ess evolv es. Topics er ed include: st at ement s com p let ed su cov ccessf ully. List ing of MY_STUDENTS. LST giv es t he f ollow ing f iv e lines: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Table dropped. TableDat created. a t y pes and comp osit e st r u ct u re 1 row created. 1 rowEr created. r or han dling and except ions Commit complete. I nt er - pr ocess com mu nicat ions By defDeclar ault , tat he iv e spconst ool f ile r aint show s, including s only t hep su rimccess ar y kor ey ,failur u nique, e of ftor h eeign SQLk st ey, at em ch eck ent, subm and mituch t ed. You hav e esev eral opt ions if y ou w ant t he spool file t o in clu de t h e SQL st at em ent . One op t ion m or is t o in clu de t h e SQL* Plu s com man d SET ECHO ON at t he b eg in ning of y our SQL scrip t , and Pr ogrECHO am m ing igger andscr Stipt or .edThPr ur esis, tTh d ost Ed itpr ion , is anb ecause inv aluable esou rce SET OFFOracle at t heTrend ofst he isoced opt ion heirm act ical y our can for datcom abase d ev elopers, d esign er s,ECHO and pr oj ect leader s look g t oion b uild d med aintLIain easily m en t / uncom m en t t h ese com m and s. An ot herin opt is t oanemb ST t r uly int ellig en t ,com com SQL* Plus mplex andsdat w itabases. h in y our scr ip t . [ Team LiB ]ex t ension for a SPOOL f ile is " LST" on Wind ow s and UNI X, b ut " LI S" on Op en VMS. The d ef ault You can specify t h e ext ension of a spool f ile ( e.g ., you m igh t w ant t o act u ally sp ool t ext w her e t he spooled t ext is a ser ies of SQL st at em en t s, t hen ru n t he ou t put as a SQL scr ipt ) . This spool com m and w ould specif y a SQL f ile ex t ension.

[ Team LiB ]

SPOOL filename.SQL

The f ollow in g scr ipt sat isfies a com m on requ est : gener at e t he t able count s for all t ables. Th e follow ing is a SQL scr ipt t hat sp ools out pu t consist ing of SQL st at em ent s.

-- filename GEN_COUNTS.sql spool GEN_COUNTS_OUT.SQL • Table of Content s SELECT 'select count (*) from '||table_name||';' Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on FROM user_tables; By Kevin Owens spool off

Prent ThePub oulish t puer:t is a ice scrHall ipt PTR of SQL st at em ent s. How ever , t h e out pu t , w hich is t he f ile PubCOUNTS_OUT. Dat e: Decem ber 0SQL, 5, 2 003con t ains som e unw an t ed t ex t ( specifically , a heading and t h e GEN_ feedback show t h33 e -0num b er of r ow s select ed) . Th e r esult in g spool file out p ut is: I SBN: 0- 13ing -0 850 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t 'SELECTCOUNT(*)FROM'||TABLE_NAME||';' Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed ---------------------------------------------------- Query Langu age ( SQL) , an d tselect eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. count (*) from STUDENTS; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 1 row selected. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sininat esseevolv es. Topics cov er ed Elim t h e heading inf or mat ioninclude: and SQL* Plus f eed back w it h SET TERM OFF and SET FEED BACK OFF. The rev ised scr ipt is: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res -- filename GEN_COUNTS.sql set heading off Dat a t y pes and comp osit e st r u ct u re set pagesize 1000 set term Er r or off han dling and except ions set feedback off er - pr ocess com mu nicat ions spoolI ntGEN_COUNTS_OUT.SQL SELECT 'select count (*) from '||table_name||';' at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch FROM Declar user_tables; or e spoolm off set heading on Pr ogrfeedback am m ing Oracle set on Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly set term on int ellig en t , com plex dat abases. [The Team LiB ] GEN_COUNTS. SQL script now gener at es just a SQL scrip t . The f ollowin g w ou ld b e t he cont ent s of GEN_COUNTS_ OUT. SQL

[ Team LiB ] select count (*) from STUDENTS; select count (*) from PROFESSORS;

The ou t pu t scrip t is GEN_COUNTS_OUT. SQL, w hich w ill p er for m r ow cou nt s f or each t ab le. We can r un GEN_COUNTS_ OUT and g et t hese num b er s b ut t he out put w ill only show r ow count s. Th e t able n am e is need ed as w ell as t h e r ow count . The SQL g en er at ion scr ipt , GEN_ COUNTS. SQL, u nder goes a mod if icat ion . The follow in g scr ipt now includ es a SQL SELECT FROM DUAL st at em en t t h at w ill spool SET ECHO com m and s.



Table of Content s

-filename GEN_COUNTS.sql Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on set heading off By Kevin Owens set pagesize 1000 set term off set feedback off Pub lish er: Prent ice Hall PTR spool GEN_COUNTS_OUT.SQL Pub Dat e: Decem ber 0on' 5, 2 003 SELECT 'set echo from dual; I SBN: 013 -0 850 33 -0 (*) from '||table_name||';' SELECT 'select count 44 8 FROM Pages: user_tables; SELECT 'set echo off' from dual; spool off set heading on set Ef fectfeedback ively creaton e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t set on ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d Kevinterm Ow ens t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. The oueasyt pu t ftile, GEN_COUNTS_OUT. w ill nowt his p r ovide w it h srow count s an he t ab le Using o- follow inst r uct ions an dSQL, ex am ples, book us pr esent t echniq ues t od t take nam es.ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our adv ant dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y set echo on Com plex r ule orcem en t select count (*)enf from STUDENTS; select count (*) from PROFESSORS; PL/ SQL p r ogr am un it s and langu age f eat u res set echo off Dat a t y pes and comp osit e st r u ct u re For t his ex am ple w e used t hr ee SQL* Plu s com m and s: HEADI NG, PAGESI ZE FEEDBACK, and TERM.Er r or han dling and except ions I nt er - pr ocess com mu nicat ions HEADI NG is a session set t in g t hat su ppr esses t he heading of SELECT r esult s. Your Declar iv e opt ion satar e: const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Tr igger SETOracle HEADING ON s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , SET com HEADING plex dat abases. OFF [ Team LiB ] ZE set t o 100 0 w ill d isplay y our out pu t as one st r eam of record s w it h no b r eak s. PAGESI PAGESI ZE of 0 su ppr esses a heading and br eak s. I f y ou w ant a heading f ollow ed by a long r ep ort w it h no br eak s, t hen set PAGESI ZE t o a lar ge nu mb er and SET HEADI NG ON.

FEED is also a session set t ing t hat supp resses such m essages as t h ose t hat [ Team LiBBACK ] indicat e t h e nu mb er of row s t hat w er e up dat ed or select ed. Your op t ions ar e: SET FEEDBACK ON SET FEEDBACK OFF TERM is a useful feat ur e t h at sup pr esses SQL* Plu s out p ut wh en u sed in conj un ct ion w it h t he SPOOL comm an d. Wh en y ou set TERM OFF inside a scr ipt and you ar e spooling out p ut , t he r esu lt s are in y our sp ool file—only . This is a v alu able feat u re for scrip t s t hat spool ou t put and cont ain m any SQL st at em en t s. Your op t ions ar e: SET TERM ON •

SET TERM OFF s Table of Content

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

[ Team LiB ]

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.9 Command Line Arguments You can u se posit ion al par am et er s w it h t he sy m bols: &1, &2, &3 , and so f ort h . Here is an ex am p SQL scr ipt t hat t ak es t w o p aram et ers. Th e int ent here is for t h ese ar gu m en t s t o b e passed on t h com man d line; fir st , t he sou rce code of t h e scr ipt ( a t ot al of fiv e lines includin g an init ial com m e t hen t he session t hat r uns it .

•-- filename Table of Content s MY_QUERY.sql

my_query.sql line 1

Pr ogr am m ing Oroff a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on set verify

SELECT * FROM students By Kevin Owens WHERE student_name = '&1' AND college_major = '&2';

my_query.sql line 5

Pub lish er: Prent ice Hall PTR

SQL> John Business Pub@my_query Dat e: Decem ber 0 5, 2 003

Run with 2 parameters

I SBN: 0- 13 -0 850 33 -0

STUDENT_ID STUDENT COLLEGE_MAJOR STATUS Pages: 44 8 ---------- ------- -------------------- -----A101 John Biology Degree A102 Mary Math/Science Degree SQL> Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. The com m and SET VERI FY OFF is a SQL* Plu s session com m and t hat m er ely supp resses t h e Using" easyt o-and follow d ex am ples, pr esent t echniq ake bef ore" " aftinst er "r uct subions st it utan ion values. Yout his getbook " cleaner " outs put w it hues v er tifoy t of f. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat abThe asesp tar o amet incorer por siness ules hichI ar t o man m odif as t he s at ar ee bu ex act subrst it ut w ions. f te heeasy p ar amet er age exp rand ession y ouy pass needs t o be bu sin qu essotevolv cov er ed include: es w ites. h inTopics t he SELECT st at em ent , t hen em bed t he sub st it ut ion par am et er ( &1 and &2 ) w single q uot es. g tconst aint s inon t h teh dat a dict ion ar y ar e " Joh n" and " Business. " Th ese ar e in " I nit ial The arView g uminen s w e rpassed e com m and line St r ing comp arisons w it h in SQL ar e case sen sit iv e; t hat is, " Business" is not t he sam e as " BUSI N Com plex r ule enf orcem en t We can get ar oun d t his. We can reliev e t h e end user fr om b eing concern ed w it h case b y using S fu nct ions: I NI TCAPS( ) , w h ich conv er t s a st r in g t o init ial caps, UPPER( ) an d LOWER( ) . PL/ SQL p r ogr am un it s and langu age f eat u res The p ar amet er s &1 an d &2, em bedd ed in sin gle qu ot es, can fu rt her be em bedded as ar gu ment s Dat a t y pes and comp osit e st r u ct u re Or acle SQL fu nct ion. The follow ing is a scen ario t hat places a comm an d line arg um en t w it h in sin qu ot es fu rtdling h er , wand it h in an Orions acle SQL fu nct ion, UPPER( ) . Er and r or han except The f ollow ex am com ple is a nicat p ar amet I nt er in - prg ocess mu ions er - dr iven dat a dict ionar y quer y . Dat a dict ion ar y view s, such dat a dict ionar y v iew USER_TAB_COLUMNS, st or e v alu es in all u pper case. You w an t t o k now all and colum nam t hatr aint cons, t ain a colu mpnrim n am STATUS, or f or possibly w it hchaeck nam e sim ilar t o ST Declarn at iv e es const including ar yedk ey , u nique, eign k ey, , and m uch The f ollow m or ein g SQL st at em ent is a st ar t ing point . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. SELECT table_name, column_name FROM user_tab_columns WHERE column_name LIKE '%ST [ Team LiB ]

This SQL q uery can be generalized in t o a par am et er - dr iv en script . To d o t h is, f ir st m ake t he colu nam e a com m and line ar gu m en t . Secon dly, allev iat e t he need for t he u ser t o t y pe in upp er case

bu ilt - in fLiB unct [ Team ] ion upp er case.

-- filename QUERY_V1.sql query_v1.sql line 1 set verify off SELECT table_name, column_name FROM user_tab_columns WHERE column_name LIKE UPPER('%&1%'); query_v1.sql line 5

The af or em ent ioned scr ipt , QUERY_V1 . SQL, allow s a user t o look f or any t able and colum n w it h colum n n am e lik e " STATUS. " Th e user can t y pe " St at us, " " st at us, " or " STat us. " •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

SQL> @query_v1 status Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

The sy m bol 0-n 13 ot-0 at850 ion33(-0 &1 , &2 , et c.) is used f or posit ional par am et er s passed on t he com m and lin I SBN: can in ser t n am ed par am et er s an d b e pr om pt ed for t heir valu e. Th is scr ipt per for m s t he sam e qu Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St rline uct ur ed -- filename QUERY_V2.sql query_v2.sql 1 Query Langu age ( SQL) , an d tset eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. verify off SELECT table_name, column_name Using t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake FROM easyuser_tab_columns adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our WHERE column_name dat ab ases t o incor por at e bu siness r ules wquery_v2.sql hich ar e easy t o man6age and m odif y as t he LIKE UPPER('%&column_name%'); line bu sin ess evolv es. Topics cov er ed include: Ex ecu t ion of t he af orem en t ioned scr ipt b y t y ping t he scr ipt nam e only p rom pt s you f or " colum n_ View in g const r aint s in t h e dat a dict ion ar y par am et er value. Follow in g t he p rom pt , w e ent er " st at us. " Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re SQL> @query_v2 EnterEr value r or hanfor dlingcolumn_name: and except ionsstatus TABLE_NAME I nt er - pr ocess com mu nicat ions COLUMN_NAME ----------------------------- ----------------------------Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch STUDENTS STATUS m or e Pr ogr am iggerpar s and Ster ors,edsuPrchoced ur esand , Th&2, ir d Ed it ion is an inv valuable r esou What if wmeing havOracle e positTr ional amet as &1 and d o, not pass alues on t he rce com m for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t uly ent line? I n t hat case w e ar e p rom p t ed w it h a st r ing t hat r eq uest s t he inp ut valu e for t he arr gum int t , com abases. " 1,ellig " " 2,en " and so plex for t hdat . The f ollow ing is t h e r esult of r unn in g t he f ir st q uer y w it hout passin g com m line ar gu ment s. W e ar e pr om pt ed f or t h e par am et er v alue. [ Team LiB ]

[SQL> Team@query_v1 LiB ] Enter value for 1: status TABLE_NAME COLUMN_NAME -------------------------- -----------------------------STUDENTS STATUS

You can p rov ide y our ow n p rom p t . The f ollowin g, QUERY_V3, in clu des a SQL* Plus ACCEPT st at e t hat specif ically ask s for t he v alue of t h e " colu mn _nam e" p ar amet er .

-filename QUERY_V3.sql query_v3.sql line 1 • Table of Content s set verify off Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on accept column_name prompt 'Enter a column name: ' By Kevin Owens SELECT table_name, column_name FROM user_tab_columns WHERE column_name Pub lish er: Prent ice Hall PTR LIKE UPPER('%&column_name%'); query_v3.sql line 6 Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 SQL> @query_v3 44 8 EnterPages: a column name: status

TABLE_NAME COLUMN_NAME ------------------------ ----------STUDENTS Ef fect ively creat e an d man age STATUS com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Nam es wit h in a scr ipt , su ch as " &colum n_n am e, " mak e t h e scr ipt m ore r eadab le. I f y ou use pos par ameasyet er s tbo-ecause ou roft r unant he scrip t w it ht his comm an pr d line arsgtum en t s, you Using follow yinst ucten ions d ex am ples, book esent echniq ues t o can t akest ill mak e t m orant e readab assigning e posit p aram ers t o nam ed ur par am et er the adv ag e ofleOrby acle feat ur est hsuch as ional t rig gers andetst ored pr oced esf eat u r s. es This t hat achieves allow y our obj iv e: com manpor d lin um entrsules an dwf or malarpar am ett er n ames e "m &colum dat ect ab ases t o incor ate arg bu siness hich e easy o man age lik and odif y n_ as nam t he e." You ca bot h w hen y oues. D EFI NE a cov for m ore m eaning fu l par am et er n am e w it h t he v alue of a p osit ion a bu sin ess evolv Topics er al, ed m include: par am et er . Th e follow ing scr ipt , uses " colu mn _nam e" w it hin t h e body , b ut t he scrip t im m ed iat el assig ns t o t his v ar iab le t he v alue of t h e fir st p osit ion al par am et er . View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res -- filename QUERY_V4.sql query_v4.sql line 1 Dat a t y pes and comp osit e st r u ct u re set verify off define column_name=&1 Er r or han dling and except ions SELECT table_name, column_name FROM I nt er user_tab_columns - pr ocess com mu nicat ions WHERE column_name LIKE UPPER('%&column_name%'); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e SQL* Plus p aram et ers can be passed as ar gum ent s t o a PL/ SQL pr ocedur e. The f ollowin g p rocedu tPr wogr o p am ar amet s. The Tr f irigger st p ar erorised a Pr st roced ing ; ur t hes e second is a num ber m ingerOracle s amet and St , Th ir d Ed it ion , is an. inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] PROCEDURE my_procedure (v_param_1 VARCHAR2, v_parm_2 NUMBER)

[ Team LiB ] We also h ave a scr ipt t hat accept s t w o p aram et ers: t he f irst is a st r ing, t he secon d a num b er . Fr w it hin t he b ody of t h e SQL* Plu s scr ipt , w e can inv ok e our pr ocedu re, p assing t h e valu es f r om t h com man d line. Keep in m ind t hat w e ar e passing a lit eral ex pr essing t o our p rocedur e, w hich m e if w e pass STATUS ( using no qu ot es) and 4 on t h e comm an d line, t h is is t he sam e as in vok ing t h pr oced ur e w it h

my_procedure (STATUS, 4)

This is n ot v alid. For STATUS t o be a lit er al st r ing, it m ust be in sin gle quot es. Th at is, w e w ant t follow ing exp ansion: •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

my_procedure ('STATUS', 4) Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

We m ust cod e t he follow in g sy nt ax wit h in t h e SQL* Plus scrip t : Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t 'parameter_name' Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easyfollow uctSQL ions pan d ex am t his book pr esent s t echniq ues t o t ake The SQL* Plut os call t o tinst h e rPL/ rocedur e ples, is: adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y my_procedure ('parameter_name', etc) Com plex r ule enf orcem en t When passing par am et er s t o wh er e a st rin g is ex pect ed , alw ays fur t h er em bed t he p aram et er w SQL ogr amisun s andPlus langu age res singlePL/ q uot es.p rBelow a itSQL* scrip t t fheat at uem beds t h e fir st com m and lin e ar gum ent w it h in s qu ot es. A st ored pr oced ur e is inv ok ed f rom wit h in a SQL* Plus script w it h t he SQL* Plus EXECUTE Dat a t y pes and comp osit e st r u ct u re com man d. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch -- filename QUERY_V5.sql query_v5.sql line 1 m or e set verify off define column_name=&1 Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce define other_parameter=&2 for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly . . . en SQL*Plus statements int ellig t , com plex dat abases. execute my_procedure('&column_name', &second_parameter) [ Team . . . SQL*Plus LiB ] statements

We can ex ecut e t h e SQL* Plu s scr ipt w it h t he f ollow ing :

[ Team LiB ]

SQL> @query_5 status 120

The SQL* Plu s scr ipt now in vok es t he st or ed p r ocedu re w it h t h e pr oper par am et er s.

my_procedure ('status', 120)

•The f ollow in g Table of Content t opics w ill bes cover ed. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

SET SERVEROUTPUT ON

DBMS_ OUTPUT

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 EXECUTE I SBN: 0- 13 -0 850 33 -0

SET SERVEROUTPUT ON is a SQL* Plus com m and t hat is requ ired ju st once p er SQL* Plus session Pages: 44 8 do not t y pe t his on t h e SQL* Plus com man d lin e, you w ill not see ou t put f rom DBMS_OUTPUT. From SQL* Plu s y ou can execut e an y pr oced ur e, fun ct ion , or p ack age p r ogr am by t yp in g EXECUT t he pr ogr am nam e. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d The D BMS_OUTPUT pack age h as sev eral pr ocedu r es, b ut t he pr ocedur e y ou most fr equent ly u se t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. dat a, num ber s, or t ex t is PUT_LI NE. To illust r at e, t he f ollowin g is a SQL* Plus scrip t t h at select s fr om t he STUDENTS t able. This scrip t r et ur ns st ud en t s t h at hav e a par t icular m ajor or hav e a p a Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake st at us. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y -- filename QUERY_V6.sql query_v6.sql line 1 set verify Com plexoff r ule enf orcem en t set serveroutput on set feedback offam un it s and langu age f eat u res PL/ SQL p r ogr Datp_major=&1 a t y pes and comp osit e st r u ct u re define define p_status=&2 Er r or han dling and except ions execute dbms_output.put_line('Parm 1='||'&p_major'); I nt erdbms_output.put_line('Parm - pr ocess com mu nicat ions execute 2='||'&p_status'); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch SELECT * from students m or e WHERE college_major=('&p_major') OR status=('&p_status'); Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. Passin g as par amet er s, " Mat h" for t he colleg e m ajor an d " Degr ee" for a st udent st at us: [ Team LiB ]

SQL> Math Degree [ Team@query_v6 LiB ] Parm 1=Math Parm 2=Degree STUDENT_ID ---------A101 A102

STUDENT_NA ---------John Mary

COLLEGE_MAJOR -------------------Biology Math/Science

STATUS -----Degree Degree

You w ill not ice a SQL* Plus com m and , SET FEEDBACK OFF. This is a SQL* Plu s com m and t h supp resses SQL* Plus messages. The calls t o DBMS_OUTPUT. PUT_ LI NE( ) use t he concat enat ion oper at or " | | " . This is t h e ope per for m st r ing concat en at ion. •

Table of Content s

ogr am mLiB ing ]Or a cl e ® [PrTeam

Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

2.10 SQL*Plus with Korn Shell Ther e ar e t hr ee t opics cover ed in t his sect ion. I nv okin g SQL* Plus fr om Kor n Shell I nv okin g Kor n Shell f rom SQL* Plu s Passin g ar gu m en t s bet w een lang uages To em bed SQL* Plu s w it hin Kor n Sh ell, u se Kor n Shell Here- Docum ent s. Th is Korn shell • Table of Content s langu age f eat ur e allow s " in put r ed irect ion" t o specify " in- st r eam t ex t ." The sy nt ax u ses t he Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on sym b ol " < < ," w hich is follow ed by any char act er st ring —our ex am ple uses " EOF" . Follow ing By Kevin Owens " < < EOF" is t h e inpu t - st ream t ex t consist ing of SQL* Plu s com man d f ile. The f ollow in g sh ows just a Kor n Shell scr ipt t hat pr int s t he fir st t wo ar gum ent s. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

#!/bin/ksh # KSH script to echo to parameters. echo $1 Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t echo $2 Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d # end of script t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Kor n sh ell p recedes posit ional p aram et ers wit h a " $" w hile SQL* Plu s uses " &" . We can em bed adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our a SQL* Plu s scr ipt w it hin a Kor n Sh ell scr ipt and ru n t he Kor n Shell scr ipt , passing ar gu ment s dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he on t he com m and line t hat ar e t hen passed t o t he SQL* Plus scr ipt . bu sin ess evolv es. Topics cov er ed include: The f ollow in g Kor n shell scr ipt accept s t hr ee arg um ent s: u ser nam e, passwor d , and a st r ing used View t o m at chconst colum n nam colum n_ ar nam in g r aint s in es. t h eThe dat a dict ion y e has scope w it h in t h e SQL* Plu s scr ipt . Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res #!/bin/ksh Dat a t y pes and comp osit e st r u ct u re # KSH script filename: script_01.ksh username=${1} Er r or han dling and except ions password=${2} I nt er - pr ocess com mu nicat ions column_match=${3} sqlplus –s ${username}/${password} SET AUTOT ON EXP SQL> SELECT status FROM students WHERE student_id='A101'; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t STATUS Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d -------------------t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Degree Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e ofPlan Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Execution dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he ---------------------------------------------------------bu sin es. Topics cov er edOptimizer=CHOOSE include: 0 ess evolv SELECT STATEMENT (Cost=1 Card=1 Bytes=10) 1 0 TABLE ACCESS (BY INDEX ROWID) OF 'STUDENTS' View in g const r aint sCard=1 in t h e dat a dict ion ar y (Cost=1 Bytes=10) 2

1 INDEX (UNIQUE SCAN) OF 'PK_STUDENTS' (UNIQUE) Com plex r ule enf orcem en t

PL/ SQL p r ogr am un it s and langu age f eat u res Sup pose a d ev elop er disabled t h e const rain t w it h t he f ollow in g. Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions SQL> ALTER TABLE students 2 Declar DISABLE at iv eCONSTRAINT const r aint s, pk_students including p rimCASCADE; ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Follow ingm ting h e Oracle afor em Tr enigger t ion ed D I SABLE m and, our SQL r ace show s a inv mualuable ch dif ferr esou en t rce Pr ogr am s and St or edcom Pr oced ur es , Th ir d tEd it ion , is an r esult Below disevt he SQL Trd ace r esult t hat now sour q in uery a fuain ll t able for dat. abase elopers, esign er s, —w andeprsee oj ect leader look g t oisbperf uild or anmin d mgaint t r uly scan . From t his plex w e wdat ill abases. w ant t o in vest igat e ou r SQL—may be it is not w r it t en pr op er ly or int ellig en t , com m ayb e a const r aint or ind ex h as been d rop ped. Had w e not used t his shor t an alysis t ool, w e could ely ]put our select st at em ent int o pr oduct ion hav ing it do t able scans. [ TeamlikLiB

[ Team LiB ] SQL> SELECT status FROM students WHERE student_id='A010'; Execution Plan ---------------------------------------------------------0 SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1 Bytes=10) 1 0 TABLE ACCESS (FULL) OF 'STUDENTS' (Cost=1 Card=1 Bytes=10)

You hav e t hr ee t y pes of out p ut t o consider w hen using AUTOTRACE.



Do you w ant t o ex ecu t e t he SQL st at em ent ? You m ay n ot if t h e SQL t ak es a long t im e t o r un. Long - r unnin g SQL st at em ent s ar e a reason t o t est w it h AUTOTRACE. You do h ave Content t he opt Table ion t oofsee an sex plain plan and/ or st at ist ics w it hou t f ully execut ing t he quer y.

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

You can By Kevin Owens

g et t he ex plain plan—t h e m ost usefu l piece of in for m at ion.

You can also g et st at ist ics t h at in dicat es t he nu mb er of phy sical and logical r ead s per ed ice . Hall PTR Pub lishfor er: m Prent Pub Dat e: Decem ber 0 5, 2 003

The AUTOTRACE sy nt ax is: I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

SET [EXP[LAIN]] [STAT[ISTICS]] Ef fectAUTOT[RACE] ively creat e an{ON|OFF|TRACE[ONLY]} d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easyt o-Com follow pr na esent s t echniq ues t o t ake SQL* Plus m inst an dr uct ions an d ex am ples, t his book Ex pla t ion adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SET Disables AUTOTRACE for t he dat ab AUTOT ases t o OFF incor por at e bu siness r ules w hich ar e easy t o session. man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SET AUTOT ON This com m and pr esu mes EXP and STAT. View in g const r aint s in t h e datEx a ecu dicttion y st at em en t es ar t he Com plex r ule enf orcem en t

Gener at es t he ex plain p lan

PL/ SQL p r ogr am un it s and langu age eatt he u res Gener at fes st at ist ics SET Dat AUTOT a t y pes TRACE and comp ositDo e st r u ctex u re NOT ecut e t he SQL st at em en t . Th is also pr esum es EXP and STAT. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Gener at es t he ex plain p lan Declar at iv e const r aint s, including rim y k st eyat , u f or eign k ey, ch eck , and m uch Generpat esart he istnique, ics m or e SET AUTOT TRACE EXP Sam e as SET AUTOT TRACE. STAT Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for abase TRACE d ev elopers, er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly SETdatAUTOT EXP d esign Do NOT ex ecut e SQL st at em ent . int ellig en t , com plex dat abases. [ Team LiB ]

Gener at es t he ex plain p lan

AUTOT [ SET Team LiB ] TRACE STAT

Do NOT ex ecut e SQL st at em ent . Gener at es t he st at ist ics

The AUTOTRACE opt ion, sh own h er e, exp lain s t he SQL st at em ent . I t does not ex ecut e t h e st at ement . This is u sefu l f or long r unnin g q uer ies.

SET AUTOT ON EXP

You do need a plan t able for t his t o r un. Oracle pop ulat es t he plan t able as it analyzes t h e • Table of Content s SQL st at ement . The scr ip t f or t he plan t able is f ound in t he d ir ect ory : Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

ORACLE_HOME/rdbms/admin/utlxplan.sql Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

The p lan t able, if y ou need t o k ey in , is:

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tCREATE eaches you w hat y ou n eed t o( kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. TABLE PLAN_TABLE statement_id VARCHAR2(30), Using easy- t o- follow DATE, inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake timestamp adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our remarks VARCHAR2(80), dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he operation VARCHAR2(30), bu sin ess evolv es. Topics cov er ed include: options VARCHAR2(255), object_node VARCHAR2(128), object_owner VARCHAR2(30), View in g const r aint s in t h e dat a dict ion ar y object_name VARCHAR2(30), object_instance NUMERIC, Com plex r ule enf orcem en t object_type VARCHAR2(30), optimizer VARCHAR2(255), PL/ SQL p r ogr am un it s and langu age f eat u res search_columns NUMBER, id Dat a t y pes and NUMERIC, comp osit e st r u ct u re parent_id NUMERIC, Er r or han dling and except ions position NUMERIC, cost NUMERIC, I nt er - pr ocess com mu nicat ions cardinality NUMERIC, bytes NUMERIC, Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch other_tag VARCHAR2(255), m or e partition_start VARCHAR2(255), partition_stop VARCHAR2(255), Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce partition_id NUMERIC, for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly other LONG, int ellig en t , com plex dat abases. distribution VARCHAR2(30), cpu_cost NUMERIC, [ Team LiB ] io_cost NUMERIC, temp_space NUMERIC, access_predicates VARCHAR2(4000), filter_predicates VARCHAR2(4000));

[ Team LiB ] [ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Chapter Three. Declarative Constraints 3. 1 PRI MARY KEY 3. 1. 1 Cr eat ing t he Const r ain t 3. 1. 2 Nam ing t he Const rain t 3. 1. 3 The Pr im ar y Key I n dex 3. 1. 4 Sequences •

Table of Content s

Pr ogr am m ing e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on 3.Or 1.a5clSequences in Code By Kevin Owens

3. 1. 6 Con cat enat ed Pr imar y Key 3. 1. 7 Ex t r a I nd ex es w it h Pseud o Keys

Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003

3. 1. 8 En able, Disable, and Dr op

I SBN: 0- 13 -0 850 33 -0 Pages:3.44 1.8 9 Defer r able

Opt ion

3. 1. 1 0 NOVALI DATE 3. 1. 1 1 Er r or Hand lin g in PL/ SQL Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin3.Ow ensQUE ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 2 UNI t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 3. 2. 1 Com bin in g NOT NULL, CHECK w it h UNI QUE Const r aint s Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e 3. of2.Or acle feat es such as ple t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 2 St ud en t sur Table Exam dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv Topics cov er ed include: 3. 2. es. 3 Defer r able and NOVALI DATE Op t ions 3. 2. 4 Er r or Hand lin g in PL/ SQL View in g const r aint s in t h e dat a dict ion ar y 3. 3 FOREI GN KEY Com plex r ule enf orcem en t 3. 3. 1 Four Ty pes of Er r or s PL/ SQL p r ogr am un it s and langu age f eat u res 3. 3. 2 Delet e Cascad e Dat a t y pes and comp osit e st r u ct u re 3. 3. 3 Man dat or y Foreign Key Colum ns Er r or han dling and except ions 3. 3. 4 Refer encin g t he Par ent Sy nt ax I nt er - pr ocess com mu nicat ions 3. 3. 5 Refer ent ial I nt egr it y acr oss Sch em as an d D at abases Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e 3. 3. 6 Mu lt ip le Parent s and DDL Mig rat ion Pr ogr am m ing igger s and St ionships or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce 3. 3.Oracle 7 Man y-Trt oMany Relat for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , 3. com 3. 8plex Self - dat Refer abases. ent ial I nt egr it y [ Team LiB3.] 3. 9 PL/ SQL Er ror Han dling w it h Parent / Child Tables 3. 3. 1 0 The D ef err able Opt ion 3. 4 CHECK

[ Team LiB ] 3. 4. 1 Mu lt icolum n Const r aint 3. 4. 2 Sup plem ent in g Uniqu e Const r aint s 3. 4. 3 St ud en t s Table Exam ple 3. 4. 4 Look up Tables v ersus Check Const r aint s 3. 4. 5 Car din alit y 3. 4. 6 Desig ning f or Check Con st r aint s 3. 5 NOT NULL CONSTRAI NTS 3. 6 DEFAULT VALUES •

Content s 3. 7 MODTable I FYI of NG CONSTRAI NTS

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

3.Owens 8 EXCEPTI ON By Kevin

HANDLI NG

3. 9 DATA LOADS Pub lish er: Prent ice Hall PTR

ThisPub is Dat t hee:fir st of sever al chap t er s t h at cov er en for cin g business ru les wit h const r aint s. Decem ber 0 5, 2 003 Declar at iv e const r aint s pr ov ide a cor e an d t rad it ion al st r at egy for business r ule enfor cement . I SBN: 0- 13 -0 850 33 -0 This chap t er ex plains t he h ow and w hy of d eclar at ive con st r aint s. Ch apt er 4 illust r at es t he 44 8 use of Pages: declarat iv e const r aint s an d in clu des a sam ple st ud en t 's d at a m odel. Ch apt er 5 dem onst r at es how t o ext r act declar at iv e con st raint def in it ions f rom t he dat abase dat a dict ionar y . Ch apt er 6 b eg ins a ser ies of ch apt ers on t rigg er s t hat enf or ce con st r aint s pr oced ur ally. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t This t er m f requ t r efer en ce tansw o a STUDENTS le.urTh STUD ENTS ab le( is par,t an of d Kevinchap Ow ens exakes plor es PL/en SQL, Or acle's er t o t h e Stt ab r uct ede Query Langut age SQL) t he sam ple a myodel escrt oibed in Ch eaches youdwathat ou n deed kn ow t o apt build er rob 4. Th uste an m odel d com descr plexipt dat ion abincludes ases f or an y our entbitusiness. y r elat ion sh ip d iag ram , DDL, sam p le dat a, p lu s a d escr ip t ion of t he bu sin ess r ules enfor ced. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Or acle su e ppor t s acle t he ffeat ollow SQL const r aint adv ant ag of Or uring es such as t rig gerss: and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: Pr imar y Key const r aint Unique st r raint View in gcon const aint s in t h e dat a dict ion ar y Foreign r ain t en t Com plexKey r uleconst enf orcem Ch r aint PL/eck SQLconst p r ogr am un it s and langu age f eat u res Not const t , wosit hiche is Dat aNu t yllpes andr ain comp st rreally u ct u rea sp ecial case of a Ch eck const r aint Er r or han dling and except ions [ Team LiB ] I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

3.1 Primary Key The PRI MARY KEY of a t able const r ains a sing le colu mn , or set of colum ns, t o a u nique and m an v alue—man dat or y , m ean ing t hat no colum n in t he p rim ar y k ey can ever b e null. A t able need no bu t t h is is t he ex cept ion ; m ost t ables are cr eat ed w it h a p rim ar y k ey . Con sider a t able t h at st or es infor m at ion about st ud en t s. We m ust b e able t o ident ify a st udent a associat ed wit h t h at ind ividu al st ud en t . Each st udent m ust h ave a r ow and on ly one r ow in t he S each r ow in t he STUDENTS t able sh ould id en t ify on e, and only one, st ud en t . The pr imar y k ey m e app licat ion, for ex amp le, t o p rop er ly pr ocess st u dent t uit ion bills. Ever y st udent w ill get one, and o b usiness ru le •I n addit ion t Table of Content s en for cem ent , t here ar e ot her dat ab ase m ot iv at ions. Pr im ary k eys ar par ent child r elat sst hat en for r ef dure erent egrtiitony. Ad dit ionally , a p rim ar y k ey requ ir es Pr ogr am- m ing Or a cl e ionship ® Tr i gger and Stor e dce P roce s, ial Thirin d tEdi st r uct ur e consum ing disk space t hat , w hen u sed pr oper ly, p r ovides f ast access t o t he d at a. By Kevin Owens The D DL for t he pr im ar y key const r aint can b e em bedd ed w it hin t h e CREATE TABLE st at em ent . E t w oPub sylish nt ax v er sions: a colum n con st rain t clause and a t able const r ain t clause. The p rim ar y k ey er: Prent ice Hall PTR creat ed separ at e fr om t he t able cr eat ion st at ement . This is accomp lish ed w it h an ALTER TABLE s Pub Dat e: Decem ber 0 5, 2 003 t he con st r aint w it h ALTER TABLE can be don e im mediat ely aft er t he t ab le is cr eat ed. I t can also 0- 13 -0 850 33 -0 t able isI SBN: p opulat ed. Pages: 44 8

The Oracle d at abase engine enf or ces t h e r ule of t he pr im ar y k ey con st rain t . Once y ou creat e a t a k ey , y ou ar e say ing t h at : f irst , all values f or t he pr imar y k ey ar e uniqu e; and secon d, t h ey m u st m ean s t hat no colu m n in t he pr im ar y k ey can ev er be NULL. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t En for cem ent of a const r aint canOrbe t em por ar ily enab led. This is (accomp lished Kevin Ow ens ex plor es PL/ SQL, acle's answ er tdisabled o t h e St ran uctdurlat ederQuery Langu age SQL) , an d st at ement t h eycon rainttoopt SABLE ENABLE. Onedat r eason t o fload d at a w it h a d is t eaches youand w hat ou nsteed kn ion ow s:t o DI build rob and ust an d com plex ab ases or y our b usiness. r ed uce t he load t im e. The load t im e w it h a disabled con st r aint w ill be less because index es ar e d not upeasydat ed. Using t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Wit hinases a t ran ion, ionr ules can w t emp suspend const ain t m enf or ycem dat ab t o sact incor por an at eapplicat bu siness hichorararily e easy t o man age rand odif as ent t he. I n t his cas tbu r ansact ion b y set t in g t he const r aint t o a deferr ed st at e. The dat a is loaded follow ed b y a com m sin ess evolv es. Topics cov er ed include: const r ain t is ap plied b y Or acle. Th is opt ion requ ires t h at t h e const r ain t b e cr eat ed wit h t h e DEFE You can load a int o as tin abtle h aa dict conion st raint View in g dat const r aint h ewit dat ar y disabled and, aft er t he load , enable t he const r ai app lied only t o new dat a. The old dat a, sh ould it v iolat e t he b usiness r u le, can r em ain in t h e t ab bu sin Com ess rplex ule enf orcem en t can r ule enf orcem en tapply t o dat a w ar eh ouses t hat mu st hav e hist or ical dat a available opt ion r equir es t hat t he const r aint be enabled w it h a NOVALI DATE k ey w or d. PL/ SQL p r ogr am un it s and langu age f eat u res Sever al t y pes of pr im ar y key enf orcem en t , such as DEFERRABLE and NOVALI D ATE, w ill aff ect t h a rim t y pes e . stThese r u ct u re w it h tDat he p ar y and k ey comp const osit r aint op t ions w ill use a nonu niqu e index . A conv ent ional pr ima w it hout ever at t em pt in g t o v iolat e it , even t emp orar ily w it hin a t r an sact ion, will u se a un ique in d Er r or han dling and except ions The f act t h at a t able h as a p rim ar y k ey is st or ed in t h e dat a dict ionar y. We hav e look ed at t he d I nt er - pr ocess com( see mu nicat ions USER_TAB_ COLUMNS Ch apt er 1, Sect ion 1. 6 .2 , " D at a Dict ionar y " ) , w hich is t he d ict ion ary v colum n n am es w it h in a t able. We also h ave v iew s for con st r aint s, t hese ar e USER_ CONSTRAI NT Declar at iv e const r aint s, including p rim wh ar yatk ey , u nique, or eign k ey, , and m uch USER_CONS_COLUMNS. These v iew s show t ables hav e f con st rain t s, ch aseck w ell as con st rain t n m or e Tw o m et hod s by w hich y ou can challen ge a pr im ar y k ey con st raint is t o I NSERT a du plicat e row Pr ogr am ing aOracle Tr igger and or ed Pr oced ur es , or ThUPDATE ir d Ed it ion , is anent invwaluable v alue form cing d uplicat e—inseit herStcase, t he I NSERT st at em ill fail writesou h anrce Or acl for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int elliging en t ,const com rplex Declar aint sdat is abases. on ly par t of an app licat ion. Applicat ion cod e sh ould be int egr at ed w it h co and han dle er ror s t h at p rop agat e f r om const rain t v iolat ions. I f you r applicat ion is an OLTP sy st e [cause Teama LiB ] d uplicat e insert , t he code sh ould con t ain g racefu l err or h andling . I t shou ld p rod uce a m e r espon se mor e m eaning ful t han t he generic t ex t of a const r ain t v iolat ion or an alar m ing st ack t r

[ Team Creating LiB ] 3.1.1 the Constraint This sect ion cov er s cr eat in g t he const r aint wit h t h e colu mn const r aint clau se, t ab le con st raint cla TABLE st at em en t . This sect ion w ill use a sam p le t able, TEMP, t hat has t h e follow ing descr ipt ion:

Name Null? ------------------------------ -------ID NO

Type -----------VARCHAR2(5) NUMBER

Ther e ar e sev eralofsyContent nt ax met • Table s h ods and st y les f or cr eat in g a pr im ary key : Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

1 . Colum n Con st r aint Clause 2 . Table Const r ain t Clau se Pub lish er: Prent ice Hall PTR Dat e: Decem ber st 0 5, 003ent 3 .Pub ALTER TABLE at2em I SBN: 0- 13 -0 850 33 -0

The f ollow g 8d iscussion ad dr esses t he t hr ee st y les w it h r espect t o cr eat ing a PRI MARY KEY cons Pages:in44 const r ain t s, UNI QUE, FOREI GN KEY, and CHECK, can also be cr eat ed w it h each st yle.

3.1.1.1 COLUMN CLAUSE Ef fect ively creat e anCONSTRAINT d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d The f ollow in gwcr eatyes ab le, h t w orob colum ns.d Th e colu D ases is t hef or p rim ar yb kusiness. ey . Th is is t eaches you hat ou an teed t o TEMP, kn ow two itbuild ust an com plexmn datIab y our colum n con st r aint clau se. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SQL> CREATE TABLE temp(id VARCHAR2(5) PRIMARY KEY, no NUMBER); View in g const r aint s in t h e dat a dict ion ar y Table created. Com plex r ule enf orcem en t p ris ogrcram age f eat u res On ce PL/ t heSQL t able eat un ed itr sowand s arlangu e insert ed; how ev er , an I NSERT w it h a du plicat e value for t h e c t hir d I NSERT st at em ent is a du plicat e and conseq uent ly f ails. Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions SQL> Declar insert temp ('AAA', 1); First f or row. at ivinto e const r aintvalues s, including p rim ar y k ey , u nique, eign k ey, ch eck , and m uch m or e 1 row created. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce SQL> into tempd values for datinsert abase d ev elopers, esign er s,('BBB', and pr oj 2); ect leaderSecond s look in grow. t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. 1 row created. [ Team LiB ] SQL> insert into temp values ('AAA', 3); Duplicate. insert into temp values ('AAA') *

ERROR 1: [ Team at LiBline ] ORA-00001: unique constraint (SCOTT.SYS_C006083) violated

For t he last inser t , SQL* Plus flushed an er r or m essage t o t he display. This is t he behav ior of SQL w r it in g cod e in Jav a or PL/ SQL an d an t icip at e a d uplicat e insert , w e can w r it e er ror handling cod condit ion, and han dle it g racefu lly . The d uplicat e insert err or m essag e pr efix is " ORA" . The er r or nu mb er is " - 00 001. " That is not a d and t h e num ber , b ut " ORA" and a m inus one. The af or em ent ioned err or m essag e r ef er ences " SCOTT. SYS_C006 083 " ; t h is is t he n ame of t he p This n ame w as int ern ally generat ed by Oracle du r in g ex ecu t ion of t h e CREATE TABLE TEMP st at e pr im ary key const r aint wit h a colu mn const r aint clause:



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE TABLE temp (id VARCHAR2(5) CONSTRAINT PRIMARY KEY my_constraint_name, noPub NUMBER); lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

Colum n const r aint clauses ar e quick an d ap pr opr iat e for ad h oc SQL. Tw o r est r ict ions on colum n Pages: 44 8 pr im ary key s ar e: ( a) no concat enat ed pr im ary k ey can b e declared and ( b) y ou cann ot st ipu lat e index cr eat ed on behalf of t he con st r aint . Bot h con cat en at ed k ey s an d t ablespace clauses for in d in t his chapt er . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin ens ex plor es PL/ SQL, OrCLAUSE acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 3.1.1.2OwTABLE CONSTRAINT t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. The t able const r ain t clause at t ached t he endt his of tbook he t able defins itt ion . Table r aint clau ses Using easyt o- follow inst r uctisions an d exatam ples, pr esent echniq ues const t o t ake CREATE at em entur—t just af t er allstt hored e colu s ar defin . I ft hat t here is a ysyn adv ant agTABLE e of Orstacle feat eshey such as come t rig gers and prmn oced ur eesf eated u r es allow ourt ax clause, t he st at em en t f ails and no t able is creat ed. dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: The f ollow in g illust r at es, in t em plat e f or m, a CREATE TABLE st at ement t hat declares a pr imar y k const r ain t clause allow s m ult iple const r aint s t o be in clud ed w it h a com m a separ at ing each const View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res CREATE TABLE temp (id Dat VARCHAR2(5), a t y pes and comp osit e st r u ct u re no NUMBER, Er r or han dling andKEY except ions CONSTRAINT PRIMARY (id), CONSTRAINT.. next constraint, I nt er - pr ocess comconstraint) mu nicat ions TABLESPACE etc; CONSTRAINT. . next Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e The f ollow in g cr eat es t he TEMP t ab le, u sin g a t able const r aint clau se. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] CREATE TABLE temp (id VARCHAR2(5), no NUMBER, CONSTRAINT PRIMARY KEY (id)) TABLESPACE student_data;

[ Team LiB ]

3.1.1.3 ALTER TABLE STATEMENT The ALTER TABLE st at ement is anot h er opt ion for man aging const r ain t s. Once y ou cr eat e a t able ALTER TABLE st at em ent t o m anag e con st rain t s, add colu mn s, and chang e st orag e par am et er s. T com man d r egar ding const r aint s is u sed t o perf or m t he f ollowin g:

Funct ion t o Pe rf orm



ALTER Sy nt a x

Add a con st r aint

ALTER TABLE table_name ADD CONSTRAINT etc

Dr op a const r aint

ALTER TABLE table_name DROP CONSTRAINT etc

Disable a con st r aint

ALTER TABLE table_name DISABLE CONSTRAINT etc

Table of Content s

En able a const r aint

ALTER TABLE table_name ENABLE CONSTRAINT etc

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

The f ollow in g D DL consist s of t wo DDL st at em en t s: a CREATE TABLE st at em en t an d an ALTER TA pr im ary key . I n t his exam ple, t h e const r ain t is n amed PK_TEMP. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

CREATE TABLE temp (id

VARCHAR2(5), no

NUMBER);

ALTER TABLE temp ADD CONSTRAINT pk_temp PRIMARY KEY (id); Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d The ALTER an dt h t ionrob s. An t o r emem in g sy nt ax is t o co t eaches youTABLE w hat ycomm ou n eed o as kn m owany t o op build ust appr an d oach com plex dat ab ber ases f ort he y our b usiness. Or acle need s t o perf or m t his op er at ion: Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our t o say w heat ab le you ar ewalt erinarg;e easy you begin w itage h: and m odif y as t he dat abYou aseshav t o eincor por at but siness r ules hich t o man bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y ALTER TABLE table_name Com plex r ule enf orcem en t PL/ SQLwh p ratogr un itdoing s and? langu age f eat u res Then, aram e y ou Add ing a const r aint : Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions ALTER TABLE table_name ADD CONSTRAINT I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch I t is h ighly r ecom m ended but not r eq uir ed t h at y ou in clu de a nam e for t he const r aint . Th e m or e emb ed ded in q uot es, but w ill be st or ed in t he dat a dict ion ary in u pper case. For t he t able T r ainOracle t n am eTrPK_TEMP. Pr ogr const am m ing igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] ALTER TABLE temp ADD CONSTRAINT pk_temp

Denot e t he t y pe of const r aint t hat w ill be a PRI MARY KEY, UNI QUE, FOREI GN KEY, or CHEC

[ Team LiB ]

ALTER TABLE temp ADD CONSTRAINT pk_temp PRIMARY KEY

Ther e ar e a f ew specif ic opt ions t hat f ollow t he ref er ence t o t he const r aint t yp e. For a PRI M const r ain t , d esignat e t he colum ns of t he const r aint . For a CHECK const r ain t , designat e t he for t he TEMP t ab le is creat ed wit h t h e follow ing syn t ax.

ALTER TABLE temp ADD CONSTRAINT pk_temp PRIMARY KEY (ID); •

Table of Content s

Pr ogr am m ing a cl e ® KEY Tr i gger s and e d con P roce Edi ti on For PRIOr MARY and UNIStor QUE stdure raints,sThir w ed should

desig nat e t h e t ablespace nam e of t he as a by - pr od uct of t h e con st rain t —t his t op ic is cov er ed in det ail in Sect ion 3. 1 .3 I ndex . " To design at e t h e index t ablespace, use k ey w or ds USI NG I NDEX TABLESPACE. The

gener at ed By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

ALTER TABLE temp ADD CONSTRAINT pk_temp PRIMARY KEY (ID) USING INDEX TABLESP Pages: 44 8

3.1.2 Naming the Constraint Ef fect ively creat e an d man age com plex dat abases w it h

Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches This sectyou ion w ill hatuse y ou a nsamp eed le t o tkn able, ow tTEMP, o buildt hat rob has ust an the d follow com plex ing dat descr ab ases ipt ion: f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: Name Null? Type ------------------------------ -------- -----------ID View in g const r aint s in t h e dat a dict ion ar y VARCHAR2(5) NO NUMBER Com plex r ule enf orcem en t PL/ SQL r ogr it s es anda langu The f ollow in gpex amam ple un creat t able age w it hf eat an uures nnam ed pr imar y k ey const r ain t . Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions CREATE TABLE temp(id VARCHAR2(5) PRIMARY KEY, no NUMBER); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e All const r aint s h ave a nam e and w hen no nam e is supp lied, Or acle in t er nally cr eat es on e w it h a follow ed mbying an um berTr . The is imurpor inginv fr equent equ ir es t h Pr ogr am Oracle iggerconst s andr aint St ornam ed Preoced es t,ant Th .ir Trou d Ed blesh it ion , oot is an aluablelyr resou rce dict ionar y f or t he const r aint t y pe, t able, and colum n nam e. For t he af or em ent ioned CREATE for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly TAB du plicat e t in ser t plex will pdat r oduce an err or . int ellig en , com abases. [ Team LiB ]

ORA-00001: unique constraint (SCOTT.SYS_C006083) violated

[ Team LiB ] The f ollow in g cr eat es t he t ab le and assign s t he con st r aint nam e PK_TEMP:

CREATE TABLE temp (id VARCHAR2(5) CONSTRAINT pk_temp PRIMARY KEY, no NUMBER);

A d uplicat e insert her e includes t h e con st rain t nam e as w ell. This con st r aint nam e, PK_TEMP, is t he nat ur e of t h e pr oblem . •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

ORA-00001: unique constraint (SCOTT.PK_TEMP) violated Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

Regar dless of t he sy nt ax f or m, you can alway s n ame a const r aint . Th e follow ing illu st r at es t h e T 13 -0 850 33 -0 pr im aryI SBN: key0-const r aint wit h a colu mn const r aint clause, t ab le con st r aint clause, and ALTER TABL Pages: r espect iv ely44 . 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d (1) CREATE temp t eaches you wTABLE hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. (id VARCHAR2(5) CONSTRAINT pk_temp PRIMARY KEY, no tNUMBER); Using easyo- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our (2) dat abCREATE ases t o TABLE incor portemp at e bu siness r ules w hich ar e easy t o man age and m odif y as t he VARCHAR2(5), bu sin(id ess evolv es. Topics cov er ed include: no NUMBER, CONSTRAINT pk_temp PRIMARY KEY (id)); View in g const r aint s in t h e dat a dict ion ar y (3) CREATE TABLE temp Com plex r ule enf orcem en t (id VARCHAR2(5), no NUMBER); PL/ SQL p r ogr am un it s and langu age f eat u res ALTER TABLE temp ADD CONSTRAINT pk_temp PRIMARY KEY (id); Dat a t y pes and comp osit e st r u ct u re Hav inEr g rcon sist ency o conexcept st r aintions nam es, or follow ing a f or mat , is ju st as im por t ant as nam ing t h or han dling t and st ages of a d at abase, be it dev elopm ent , t est , or pr oduct ion, it m ak es sense t o hav e pr im ary key Pr imar y er k ey t smu ar enicat comm on ly nam ed w it h one of t w o for m at s. Bot h for m at s ind icat e t h I nt - prconst ocessrain com ions t he PK designat ion and t h e t able nam e. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly 1. ellig PK_table_name int en t , com plex dat abases. 2.table_name_PK [ Team LiB ] Sup pose you j ust in st alled a new ap plicat ion an d y our en d u ser calls y ou. Wou ld y ou r at her hav e t his ap plicat ion an d g ot an Or acle err or t h at say s: SYS_C0060 83 const r ain t v iolat ion. " Or, wou ld

r[ an t his LiB app]licat ion and got an Or acle er r or: PK_TEMP. " Team I f t he const r aint nam e is PK_TEMP, y ou can qu ick ly com for t t h e caller b ecause y ou kn ow exact ly a p r im ar y k ey con st raint v iolat ion on t hat t able. Wit h out a m eaningf ul const r aint nam e, y ou w ou qu er y ing t he d at a d ict ionar y v iews DBA_CONSTRAI NTS t o t rack t h e t able u pon w hich t h at const is declared. A com m on over sig ht w h en using a dat a mod eling t ool is t o n ot nam e const r aint s. A dat a m odele concer n ed w it h sy st em r eq uir em ent s t h an con st r aint nam es. Havin g t o go back and t y pe in nu m nam es can be t edious. I f y ou u se su ch a t ool, it is w or t h wh ile t o do a sm all dem o t o see wh at D D You w ant t o m ak e sur e t he f inal D DL meet s y our cr it eria and t hat you ar e using t h e feat ur es of t t he desir ed D DL. Or acle Designer , v er y conv enient ly , w ill aut om at ically n am e pr imar y k ey const pr efix f ollow ed by t h e t able n ame.

3.1.3 The Table Primary Key Index • of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

This sect ion cov er s t h e index t h at m ust alway s ex ist as par t of t he p rim ar y k ey . Th e t opic of t ab l By Kevin Owens Refer t o Ch apt er 1, Sect ion 1. 6 .1 , " Ap plicat ion Tablespaces, " f or ad dit ional inf or mat ion on t he de creat ion of an Or acle t ablespace. Pub lish er: Prent ice Hall PTR

This sect ion w ill use a samp le t able, STUD ENTS, t h at h as t he f ollow in g d escr ip t ion: Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Name Null? Type -----------------------------------------------Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t STUDENT_ID Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er tVARCHAR2(10) o t h e St r uct ur ed Query Langu age ( SQL) , an d STUDENT_NAME VARCHAR2(30) t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. COLLEGE_MAJOR VARCHAT2(15) STATUS Using easy- t o- follow inst r uct ions an d ex am ples, VARCHAR2(20) t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he Whenev you es. cr eat e a prcov im ar , Or acle creat es an index on t he colum n( s) t hat m ake up t he bu sin esserevolv Topics er yedkey include: index alr eady exist s on t h ose colum ns, t hen Oracle w ill use t h at ind ex . in gan const r aint in t t h ion ar y . Dependin g on t h e pr im ary k ey opt ion s, t he ind e I ndexView es are in t eg ral spar ofe tdat h e aprdict im ary key non uniqu e. Defer rab le pr imar y k ey const rain t s use non uniq ue ind ex es. I n dexes ar e not used t o Com r uley enf orcem en t in dex is st ill r eq uir ed . The b en ef it s of t he in dex ar e seen wit h q ue r ule of t heplex pr imar k ey, but an I f t he p rim ar y k ey con st r aint is disabled, t h e index is d rop ped an d quer y per for m ance su ff er s. PL/ SQL p r ogr am un it s and langu age f eat u res Tables occu py p hy sical st or age. I ndex es also use ph ysical st orag e. The cr eat ion of t h e pr imar y k Dat a tfor y pes andin comp osit e st r uofct u t ablespace t hat dex. Because I /re O cont ent ion and t he f act t h at ind ex es gr ow d iff er ent ly t h place ind ex es in separ at e t ab lespaces. Er r or han dling and except ions The f ollow in g ALTER TABLE st at ement creat es t h e pr imar y k ey, plus d esign at es t he t ab lespace f o I ntTABLESPACE er - pr ocess com nicat ions I NDEX is amu key w ord p hr ase t o t h is sy nt ax . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly CREATE TABLE students int ellig en t , com plex dat abases. (student_id VARCHAR2(10), student_name VARCHAR2(30), [ Team LiB ] college_major VARCHAR2(15), status VARCHAR2(20)) TABLESPACE student_data; ALTER TABLE students

ADD CONSTRAINT pk_students PRIMARY KEY (student_id) [ Team LiB ] USING INDEX TABLESPACE student_index;

I f you d o not desig nat e a t ablespace for t he pr im ar y key ind ex , t h at in dex is built in y our default Or acle user accoun t s ar e creat ed w it h a defau lt t ab lespace. Tables and index es cr eat ed b y a u se designat ion fall in t o t h is defau lt t ab lespace. For exam ple, t h e follow ing DDL cr eat es an ind ex ob ject in t he d ef ault t ablesp ace. Because t her e clause on t he CREATE TABLE st at ement , t he t ab le is also creat ed in t h e defau lt t ab lespace.

CREATE TABLE temp(id VARCHAR2(5) PRIMARY KEY, no NUMBER); •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

The f ollow in g p ut s t he TEMP t able in t h e STUD ENT_DATA t ablesp ace and t he p rim ar y k ey in t h e By Kevin Owens t ablespace. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 temp(id VARCHAR2(5), no NUMBER) CREATE TABLE tablespace STUDENT_DATA;

ALTER TABLE temp ADD CONSTRAINT pk_temp PRIMARY KEY (ID) Ef fect ively USING INDEX creat TABLESPACE e an d man age student_index; com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. To cr eat e t ables and ind ex es in t ablesp aces ot h er t han you r defau lt r equir es pr ivileges. I f y ou ha Using easyt o- follow r uct anivdileg ex am ples,MIt his pr esent s t echniq uesileg t o et ake r ole, t hen y ou m ay stinst ill hav e ions t he pr e UNLI TEDbook TABLESPACE—t his p riv is aut om at ica adv ant ag e of Or acle feat uryes asit ed t rigtgers and stqored pr oced es- f eat u r es TABLESPACE t hat allow y our RESOURCE r ole and gives ousuch unlim ablespace uot as. Wit hurUNLI MI TED y ou a dat ect ab ases t o incor por at e bu siness w hich arteabeasy t o man m odift yh easprtivilege he obj s in any t ablesp ace in clu dingr tules he SYSTEM lespace. Forage t hisand r eason, is of t en bu sin ession evolv es. Topics covt ab er ed include: app licat developer s and lespace qu ot as ar e added. The ch ange m ade t o d ev elop er accoun t s is similar t o t he ch ange m ad e t o t h e SCOTT accou nt as View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res REVOKE UNLIMITED TABLESPACE FROM SCOTT; a t y pes and QUOTA comp osit e st r u ct u reON STUDENT_DATA; ALTERDat USER SCOTT UNLIMITED ALTER USER SCOTT QUOTA UNLIMITED ON STUDENT_INDEX; Er r or han dling and except ions ALTER USER SCOTT DEFAULT TABLESPACE STUDENT_DATA; I nt er - pr ocess com mu nicat ions Ch eckDeclar y our at account pr iv ileges an d t ab lespace it h t hef or f ollowin g SQL. Pr,ivand ileges and r oles iv e const r aint s, including p rim ar yq uot k eyas , uw nique, eign k ey, ch eck m uch y our Or acle accou nt are quer ied fr om t he dat a dict ionar y v iew s USER_ROLE_PRI VS and USER_S m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. column role_priv format a30 [ Team LiB ] SELECT 'ROLE: '||granted_role role_priv FROM user_role_privs UNION SELECT 'PRIVILEGE: '||privilege role_priv

FROM [ Team LiBuser_sys_privs; ] ROLE_PRIV -----------------------------PRIVILEGE: SELECT ANY TABLE PRIVILEGE: CREATE ANY MATERIALIZED VIEW ROLE: CONNECT ROLE: RESOURCE ROLE: SELECT_CATALOG_ROLE

To see t ablespace qu ot as, quer y USER_TS_ QUOTAS:



Table of Content s

Pr ogr am mtablespace_name, ing Or a cl e ® Tr i gger s and Stor e d P roceFROM dure s, user_ts_quotas; Thir d Edi ti on SELECT max_bytes By Kevin Owens

The af or em ent ioned SQL w ill r et u r n a m in us 1 f or any t ab lespace f or w hich y ou hav e an un lim it e exam Pubple: lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

TABLESPACE_NAME MAX_BYTES ------------------------------ ---------Ef fect ively creat e an d man age com plex dat abases STUDENT_DATA -1 w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er -1 t o t h e St r uct ur ed Query Langu age ( SQL) , an d STUDENT_INDEX t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easyt o- follow ions an ples, ace. t his book s t st echniq An index is an obj ect inst t hatr uct is creat ed dinexaam t ablesp I t is aprp esent hy sical r uct urues e t ht oatt ake consum es dis adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat our creat e a Pr imar y Key or Uniqu e const rain t , an index is eit her aut omat ically creat ed allow or an yex ist in dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he r eu sed. bu sin ess evolv es. Topics cov er ed include: An index is based on a t r ee st r u ct u re. I n dexes ar e used by Or acle t o ex ecut e SELECT st at em ent s SELECT using an in dex is gener ally f ast er t han a SELECT t h at d oes n ot u se an ind ex . View in g const r aint s in t h e dat a dict ion ar y I ndex es are generally cr eat ed in t ablesp aces separ at e fr om t ablespaces f or t ables. I n dexes f r om Com plexof r all ule inenf orcem up a por t ion dexes in en ant applicat ion. A t ablesp ace for in dexes w ill hav e ind ex es fr om p rim index es fr om u nique con st r aint s, an d in dexes cr eat ed t o sp eed up select ed q ueries. PL/ SQL p r ogr am un it s and langu age f eat u res Figur e 3- 1 illust r at es t he phy sical separ at ion of t he ind ex st r uct u res an d t able st ru ct ur es. Th e le Dat a t y pes and comp osit e st r u ct u re r ep r esent s a t ablesp ace for ind ex es. All index st r uct ur es ph ysically ex ist in t he f iles f or t his t able illust rat es t he allocat ion of t ab les. Tables ph ysically ex ist in t he f iles f or t h e STUD ENT_DATA t ab Er r or han dling and except ions I nt er - pr ocess com mu nicat ions

Figu r e 3 - 1 . Pr i m ar y Key I n dex e s.

Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

To d et er m ine t h e phy sical sp ace allocat ed by t h e STUDENTS t ab le and t he p rim ar y k ey in dex, qu and DBA_ DATA_FI LES. Th e follow ing illu st rat es a SQL* Plus session quer y against t hese view s. B • Table of Content s begin w it h DBA, y ou need eit her t he D BA r ole or SELECT_ CATALOG_ROLE role ( refer t o Ch apt er Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on You Can See, " for ad dit ional in for m at ion on dat a dict ionar y v iew s) . By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

SQ1> I SELECT a.extent_id, SBN: 0- 13 -0 850 33 -0 2* Pages: 44 8 a.segment_name, 3* b.file_name, 4* round(a.bytes/1024) KBytes 5* FROM dba_extents a, 6* dba_data_files b Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t 7* WHERE segment_name in ('STUDENTS','PK_STUDENTS') Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 8* AND a.file_id=b.file_id; t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. SQL> Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our The r esult f r om t he pr ev ious code will p rod uce som et h in g lik e t h e follow ing. dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y EXTENT_ID KBYTES Com plexSEGMENT_NAME r ule enf orcem enFILE_NAME t --------- ------------ -------------------------- -----0 pSTUDENTS D:\. .\STUDENT_DATA01.DBF 60 PL/ SQL r ogr am un it s and langu age f eat u res 0 PK_STUDENTS D:\. .\STUDENT_INDEX01.DBF 60 Dat a t y pes and comp osit e st r u ct u re The pEr r ev r or ious han oudling t put and showexcept s t h ations t h e index cr eat ed fr om t h e pr im ary key init ially consum es 60K o STUDENT_I NDEX01. DBF. This allocat ed sp ace is in a file, separ at e f r om w her e t he in it ial 60K of I ntSTUDENTS er - pr ocess tcom for t he able.mu nicat ions Declar at iv e constcolu r aint s, ,including p rim ar yisk tey nique, k ey, ch eck andstm uch. When The SEGMENT_ NAME mn PK_STUDENTS, he, u nam e of f tor h eeign index , not t he, con r aint m or k ey con st e r aint , an in dex is creat ed w it h t h e same nam e. That is t he sit uat ion discussed ear lier. T dif fer if t he in dex is creat ed fir st and t h en t he con st r aint is cr eat ed. When a pr im ary key or u niqu Pr ogred, am m Oracle igger oced ur eson , Th ir dsam Ed iteion , is invt aluable esou .rce creat Oring acle look sTr for an sinand dex St onort ed he Pr t ab le and t he colu m an ns of he con str raint I f su c for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly t hat ind ex is u sed, regar d less of t he in dex nam e. int ellig en t , com plex dat abases. The f ollow in g p ar agr aphs ex plain t he af orem ent ioned SQL* Plu s qu er y t h at select s d at a dict ionar [t wTeam ] o v iewLiB s: DBA_EXTENTS an d D BA_DATA_FI LES. Ob ject s t hat r eq uire disk sp ace are also called segm ent s. A t able is a r elat ional ob ject , bu t it is a seg m en t —it u ses disk space. You quer y DBA_SEGMENTS t o g et t he phy sical at t r ib ut es of t ables,

clust er s,LiB and [ Team ] m at er ialized view s—any obj ect t hat r eq uir es d isk cap acit y . St or ed pr ocedu res an d seg m en t s—t hey ar e object s t h at ar e def in ed in t he dat a d ict ion ary and t heir definit ion s ex ist in t For ever y seg ment , t her e ar e one or m or e ex t en t s. An ex t ent is a cont igu ous set of d at abase blo A t able is a segm ent . Th e t able segm en t can consum e 15 cont igu ous b lock s on disk, wh er e each t hr ou gh 15, t imes t h e 4K block size, y ield s 60K. This is one ex t ent . Th er e can be ot h er ex t ent s. E cont igu ous series of 15 block s, each block being 4K. Block sizes can v ar y, and so can t h e size an The q uer y result sh ow s t hat t her e is 60 K of cont igu ous block s allocat ed for t he ind ex an d 60K of allocat ed for t he STUDENTS t able. This is w h at is f irst allocat ed just as a r esult of cr eat in g t he t a t he 60K fills up , t he t able or ind ex w ill ex t en d t o anot her 60K. The d at afile for t he STUDENT_ DA We ar e on ly usin g 60K of t hat . The d at a d ict ion ary v iew s DBA_SEGMENTS, D BA_EXTENTS, and DBA_D ATA_ FI LES ar e t h ree of m v iew s t h at p rov ide d et ailed infor m at ion about space allocat ion of seg ment s. •The f ollow in g Table of Content su mm ar izes st he r elat ion ship b et ween t he p rim ar y k ey const r aint and t he in dex. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

An index can be cr eat ed on any colum n or set of colu mn s ot her t h an t he p rim ar y k ey . Wh e st at ement t hat cr eat es a pr imar y k ey, regar d less of t he sy nt ax , an ind ex is alw ay s cr eat ed, t hose ex act colum ns d oes n ot alr eady exist . A pr im ary k ey and un ique const r aint ar e not t h Pub lish er: Prent ice Hall PTR est ablish in g an ind ex . Fr equent ly , m any ot her index es ar e cr eat ed as a m ean s t o achiev e o Pub Dat e: Decem ber 0 5, 2 003

I SBN: 0- 13 The f act t h-0at850 t h33er-0e is a pr im ary key const r aint is w h olly defined w it h in t he dat a dict ionar y . Pages: 44 8e ex cept t he dat a dict ionar y t ab lespace t hat r ecor ds t his const r ain t d ef init ion. How any w her int egr al p art of t he con st r aint . I t is an obj ect , t akes space, and can be v iew ed fr om t h e dat USER_OBJECTS and USER_I NDEXES, USER_ SEGMENTS, and USER_EXTENTS.

p r imcreat ar y ke ey st r aint challen ged wit NSERT UPD ATE stab at em Ef fectA ively an con d man age can com be plex dat abases wh it hanOrIacle! Syand st ems and dat aseent ex—t perhtese h ichexwplor e can ly at em p t tansw o violat r ain t . Th e index gener b y, tan hedp r im Kevinby Owwens es possib PL/ SQL, Ortacle's er teo t the h e const St r uct ur ed Query Langu ageat(ed SQL) does p rov ide a valu able m echan ism for op t imizing SELECT st at ement s. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 3.1.4 Sequences dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: This sect ion w ill use a samp le t able, STUD ENTS, t h at h as t he f ollow in g d escr ip t ion: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t Name PL/ SQL p r ogr am un it s and languNull? Type age f eat u res ------------------------------ -------- -----------STUDENT_ID VARCHAR2(10) Dat a t y pes and comp osit e st r u ct u re STUDENT_NAME VARCHAR2(30) Er r or han dling and except ions COLLEGE_MAJOR VARCHAT2(15) STATUS VARCHAR2(20) I nt er - pr ocess com mu nicat ions Declar at iv et able constwritaint s,im including p rim ar y k ey nique, ey, ching eckDDL. , and m uch The STUDENTS h pr ar y key const r aint is , cru eat ed wf or it heign t he kfollow m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. CREATE TABLE students [ (student_id Team LiB ] VARCHAR2(10), student_name VARCHAR2(30), college_major VARCHAR2(15), status VARCHAR2(20)) TABLESPACE student_data;

[ALTER Team TABLE LiB ] students ADD CONSTRAINT pk_students PRIMARY KEY (student_id) USING INDEX TABLESPACE student_index;

For our st u dent sy st em dat ab ase, w hat do w e use f or a STUDENT_ I D ? On e opt ion is t o generat e for each st udent t hat ent er s t he colleg e. We could use social secur it y num b er s, inf orm at ion fr om dr iv er ' s license dat a. An alt er nat iv e is f or t he ap plicat ion code t o aut o- generat e st u dent I D nu m b add ed t o t he d at abase. Dat ab ases h andle au t o- gener at ed colum ns in a v ar iet y of w ays. SQL Ser ver u ses an I DENTI TY c seq uences. W e st art w it h cr eat ing a sequence t h at is an obj ect . The ex ist ence of t hat obj ect is st dict ionar y . The sequence alw ay s has st at e in for m at ion, such as cur r en t v alue, and t h at cont ex t r dat a dict ionar y . Once y ou cr eat e a sequ en ce you can quer y t he at t rib ut es of t hat seq uence fr om v iew USER_SEQUENCES. •

Table of Content s

A sequence t ribsutand es,Stor NEXTVAL CURRVAL: Pr ogr am m ing h Oras a cltew ®oTrat i gger e d P roce and dure s, Thir d Edi ti on By Kevin Owens

Se que nce At t rib ut e

D e scri pt i on

Pub lish er: Prent ice Hall PTR sequence_name.NEXTVAL This ev aluat es t o t he nex t h ighest v alue. Pub Dat e: Decem ber 0 5, 2 003

sequence_name.CURRVAL This ev aluat es t o t he v alue t h at w as r et ur ned fr om t h e m ost r ecent N I SBN: 0- 13 -0 850 33 -0

Pages: 44 8

We can ex per im en t w it h seq uences r igh t w it hin SQL* Plus as illust r at ed wit h t h e follow ing scr ipt . t ext t h at f ollow s cr eat es a seq uence nam ed MY_SEQUENCE an d t hen uses t hat sequ en ce t o inser t able, also cr eat ed her e. The f irst st at em ent cr eat es a sequence w it h defau lt s, w hich m eans t h at t hat seq uence, t he v alue f or NEXTVAL w ill be t he nu mb er 1. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv antCREATE ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SQL> SEQUENCE my_sequence; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he Sequence created. bu sin ess evolv es. Topics cov er ed include: SQL> CREATE TABLE temp(n NUMBER); Table created. View in g const r aint s in t h e dat a dict ion ar y SQL> Com INSERT temp VALUES (my_sequence.NEXTVAL); plex INTO r ule enf orcem en t 1 row created. PL/ SQL p r ogr am un it s and langu age f eat u res SQL> / Repeat the last insert. 1 rowDat created. a t y pes and comp osit e st r u ct u re SQL> Er / r or han dling and except ions 1 row created. I nt er - pr ocess com mu nicat ions

Repeat the last insert.

SQL> INSERT INTO temp VALUES (my_sequence.CURRVAL); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch 1 row created. m or e SQL> SELECT * FROMTr temp; whaturis Pr ogr am m ing Oracle igger s and St orNow, ed Pr oced es ,in Th irthis d Ed ittable? ion , is an inv aluable r esou rce N for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly ---------int ellig en t , com plex dat abases. 1 [ Team LiB2] 3 3

The k ey LiB wor d [ Team ] START WI TH desig nat es t h e st art in g p oint of a seq uence. To r ecr eat e t he sequ en ce of 10 :

SQL> DROP SEQUENCE my_sequence; Sequence dropped. SQL> CREATE SEQUENCE my_sequence START WITH 10; Sequence created. SQL> SELECT my_sequence.NEXTVAL from dual; NEXTVAL ---------- Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and 10 •

Stor e d P roce dure s, Thir d Edi ti on

By Kevin Owens

I f you shu t t h e dat ab ase d ow n, st ar t it back up , and r epeat t h e pr ev ious t hr ee I NSERT st at em en Puber lish Prent icein Hall nu mb s er: w ill cont uePTR w it h 4, 5 , and 6. They w ill con t inue sequ en cing b ecause t h e st at e of t he s m aint in t h eberdat Pubained Dat e: Decem 0 5,a 2dict 003 ionar y. When t he d at abase is shut dow n, t he st at e of t hat sequence n in t he sy st em t ablespace I SBN: 0- 13 -0 850 33 -0 d at afile. Pages: 44 8

Sequences can b e creat ed so t hat t he n um ber s eit her cy cle or st op sequ en cin g at som e m axim um t his ar e CYCLE and NOCYCLE. The I NCREMENT BY int er v al can cr eat e t he sequ en ce t o incr em ent nu mb er ; t he d ef ault is 1. Th e CACHE opt ion pr e- allocat es a cach e of num ber s in mem or y for im p The f ollow in g illust r at es a sequence t h at w ill cy cle t h r ough t he values: 0 , 5, 10, 15, an d 20, t hen Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv antCREATE ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SQL> SEQUENCE sample_sequence dat2* ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he MINVALUE 0 bu 3* sin ess evolv es. Topics cov er ed include: START WITH 0 4* MAXVALUE 20 5* INCREMENT BY 5 View in g const r aint s in t h e dat a dict ion ar y 6* NOCACHE 7* Com CYCLE; plex r ule enf orcem en t Sequence created. PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Sequence nu m bers are n ot t ied t o an y t able. Ther e is no depend en cy b et ween any t ab le and a s no w ay o khan nowdling t hat and y ou except ar e u sing Er rtor ionsa par t icu lar seq uence t o p opulat e t he pr im ar y key of a sp ecif I f youI nt d rop and r ecrcom eat emu a nicat sequ ions en ce y ou m ay possibly, t em p orar ily, inv alid at e a st or ed p rocedu r er - pr ocess seq uence. This w ould occu r if a st or ed p rocedur e includ es t he sequence w it h NEXTVAL or CURRV Declar at iv.eOnce constt rhaint s, uence including rim ed ar y, tkhe ey ,stuor nique, f or eign ey, ch es eckinv , and uchce t he SQL st at ement e seq is drpopp ed pr ocedu re kbecom alid.mOn or e re w ill be com piled and v alid at ed at r un t im e. t he prmocedu Pr ogr ing Oracle igger syou andcan St oruse ed it Pr toced urulat es , eThany ir d colum Ed it ionn , in is any an inv rce On ce am y oumcreat e a seqTruence o pop t abaluable le. For rt esou h is r eason for dat abase elopers, er s, tand oj ect s look g t o b uild an d mpose aint ain t ropulat uly caref ully namdeev seq uencesdtesign o r eflect h eir pr u se an dleader rest r ict seqin uences t o t he pur of p ing int ellig en t , com plex dat abases. I f t he p rim ar y k ey is generat ed by a seq uence, t he sequence should be nam ed w it h t he f ollowin g [ Team LiB ]

table_name_PK_SEQ [ Team LiB ] Using t h is sy nt ax, a seq uence dedicat ed t o t he generat ion of pr im ar y key v alues in t he STUDENT nam ed:

STUDENTS_PK_SEQ

The v iew , USER_SEQUENCES, sh ows t he at t r ibu t es of all seq uences in a schem a. I f w e see a seq STUDENTS_PK_ SEQ, w e ar e q uit e cert ain t his sequ en ce is u sed t o popu lat e t he p rim ar y k ey colu t able. We are cer t ain on ly becau se of t he sequence nam e, not f rom any ot h er d at a d ict ion ary in f •

Table of Content s

Pr ogrcom am mplet ing Or a cl eL ® tTr gger e d P roce dure s, Thirpr d Edi on The e DD o icr eats eand t heStor STUDENTS t able, im tiary

k ey const r ain t w it h t ablespace clau se

tByhe follow in g: Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

CREATE TABLE students Pages: 44 8 (student_id VARCHAR2(10), student_name VARCHAR2(30), college_major VARCHAR2(15), status VARCHAR2(20)) TABLESPACE student_data; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER Ow TABLE students t eaches you w hat y ou n eed t o kn owPRIMARY t o build KEY rob ust an d com plex dat ab ases f or y our b usiness. ADD CONSTRAINT pk_students (student_id) USING INDEX TABLESPACE student_index; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant agSEQUENCE e of Or aclestudents_pk_seq; feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CREATE dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

3.1.5 Sequences in Code

View in g const r aint s in t h e dat a dict ion ar y

You can u se t he NEXTVAL at t r ibu t e in an y SQL I NSERT st at em ent t o ad d a new st ud en t . Th e foll Com plex r ule enf orcem en t uses t he sequ en ce STUDENTS_ PK_SEQ t o in ser t a new st u dent . Th is cod e could be called w hen a par t of adpmission rocess, HTML f orm h t he st udent nam e, sub ject m ajor , an d st at u s. PL/t he SQL r ogr am pun it s andanlangu age f eatwu itres on t he HTML f or m—t he st ud en t I D is ev aluat ed as par t of t he SQL I NSERT st at ement . Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions public void insertStudent(String StudentName, String Declar atCollegeMajor, iv e const r aint s, including String Status) p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch { m or e try Pr ogr{am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly stmtd = conn.prepareStatement int ellig en("INSERT t , com plexINTO dat abases. students (student_id," + " student_name, college_major, status)" + [ Team LiB " ]VALUES( students_pk_seq.NEXTVAL, :b1, :b2, :b3) "); stmt.setString(1, StudentName); stmt.setString(2, CollegeMajor);

stmt.setString(3, Status); [ Team LiB ] stmt.execute(); } catch (SQLException e) { if (e.getErrorCode() == 1) { System.out.println("We have a duplicate insert."); } } }

Sect ion 3. 1 .1 , " Sy nt ax Opt ions, " illust r at es a SQL* Plus session w her e a d uplicat e insert is m et w nu mb er of min us 1 and an Or acle er r or t ext m essage. Th e afor ement ion ed Jav a p r ocedu re in clu d except ion hand ler for t h e same t yp e of pr im ary k ey const r ain t v iolat ion. Th is t r y- cat ch hand ler u • Table of Content s get Er r or Code( ) met h od, w hich ret u rn s t he f ive- d ig it ORA nu m ber—in t h is case, 1. Such an er ror Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on it w ou ld n ot b e imp ossible. Er r or han dling code is supp osed t o be used in fr equent ly , b ut it is not By Kevin m issingOwens f rom t he app licat ion. The af or em ent ioned Jav a m et hod, inser t St u dent ( ) , in ser t s STUDENTS_PK_ SEQ. NEXTVAL as t h e Pubn lish er: Prent ice Hall colum STUDENT_I D.PTR This ex pr ession " NEXTVAL" alw ays ev aluat es t o an int eg er . Even t hou gh t STUDENT_I is stber rin0 g, 1 0) , t h e seq uence r esult is imp licit ly conv er t ed t o a st r in g b y Pub Dat e: D Decem 5, 2VARCHAR2( 003 I SBN: 0- 13 -0 850 33 -0

You can m anip ulat e t he sequ en ce and use it t o bu ild a uniqu e st rin g t h at sat isfies a d esir ed f or m Pages: 44 8 VARCHAR2( 10 ) d at a t y pe f or STUDENT_ I D . Supp ose we w ant a STUD ENT_I D t o b e t he let t er " A of nine digit s. We could declare a nine- d ig it sequence f rom 1 t o 99 9, 999 ,9 99—t hen, concat enat e pr efix let t er. Our CREATE SEQUENCE st at em ent w ould f ir st declar e t h e MI NVALUE and MAXVALU I NSERT st at em ent s w ou ld t h en " zer o- lef t - pad " t h e seq uence and concat en at e t h e pr ef ix. The I NS Efself fectw ively d man age it ouldcreat be t eheanf ollow ing . com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he INSERT INTO students bu sin ess evolv es. Topics cov er ed include: VALUES ('A' || LPAD(student_id.NEXTVAL, 9, '0'), etc); View in g const r aint s in t h e dat a dict ion ar y Sequence nu m bers are a safe st r at egy f or gu aran t eeing un ique v alues. The d ef ault CREATE SEQ 27 um ber s befor e y ou cy cle ar ound —t his shou ld h andle m ost ap plicat ion s. generCom at e 10 plex nr ule enf orcem en t The au t o-SQL gener at ion of seq uences ould PL/ p r ogr amfeat un ur it seand langu age fsh eat u resnot be a reason t o f org o er ror hand lin g code. A pr ogr am u sin g t he seq uence m ay be t he m ain v ehicle for ad ding st udent s, but r are ev ent s m ay ot her Dat m eans, such ascomp SQL*osit Plus. sit uat ion could cau se a st udent t o be add ed " b y hand " —p a t y pes and e stAr ur ar ct ue re pr oblem w it h a m issed st udent , r esolved by an op er at ions p er son en t ering t h e st udent w it h SQL st aff m se t he nex t h ighest Eray r orj ust hanudling and except ions n um ber in t he STUDENTS t able f or t hat I NSERT. Th e nex t t im and ent er s a n ew st udent , it w ill gener at e t he next seq uence valu e and collide wit h w hat oper at i SQL* Plus. I nt er - pr ocess com mu nicat ions Pr oblems Declar wit athivsequences e const r aint can s, including also occurp rim w h en ar yapp k eylicat , u nique, ions are f ormig eignrat k ey, ed and ch eck a ,sequ anden mce uch is in adv r ecr eat m ed or e. I n t his case t he sequence st ar t s ov er w it h a st udent I D of 1 and causes a d uplicat e in err or h andling , t he sequ en ce does pr ovid e uniq ueness, b ut mist ak es happ en . As r ar e as a d uplic Pr ingt urOracle orsted Pr oced ur ion es , w Thillir d Edays it ion , ise an r esouoot rceing. gr ogr acefam ul m cap e of a Tr p rigger im ar ys and k ey St con r aint v iolat alw sav houinv r s aluable of t r oublesh for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases.

3.1.6 Primary Key [ Team Concatenated LiB ] I n t his sect ion w e m ake use of a t ab le, STUDENT_VEHI CLES, t hat st or es in for m at ion on v ehicles cam pus. The t able descript ion is:

[ Team LiB ]

Name -----------------------------STATE TAG_NO VEHICLE_DESC STUDENT_ID PARKING_STICKER

-------NOT NULL NOT NULL NOT NULL NOT NULL NOT NULL

Null? Type -----------VARCHAR2(2) VARCHAR2(10) VARCHAR2(30) VARCHAR2(10) VARCHAR2(10)

Your client , t h e m ot or v eh icle d ep art ment of t he school, ex pr esses a n eed, " We w ant t o t r ack st u cam pus. St u dent s com e fr om all over t h e cou nt r y w it h cars. St u dent s ar e allow ed t o k eep car s o college need s t o t r ack v eh icles. The colleg e issu es a par k in g st ick er t hat perm it s t h e car t o rem a •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Dat a m odel analy sis begins w it h lookin g at v eh icle t ag inf or mat ion . Licen se' s t ags are issued by By Owens beKevin cer t ain t hat all vehicle license t ag nu mb er s issued by New Yor k ar e uniq ue w it hin t hat st at e a fr om Calif or nia ar e u nique wit h in t h at st at e. Tag nu m bers are shor t - st r ing com binat ions of let t er We Pub canlishassu me ice t he f ollow er: Prent Hall PTR ing r ule: w it hin each st at e, all t ag s w it hin t hat st at e ar e un iq ue. Con se comPub binat of stber at e0 5,abbr Dation e: Decem 2 003ev iat ion an d t h e t ag num b er of an y st udent 's v ehicle will b e alw ays u n st udentI SBN: s. This ule 0- 13r-0 850is 33enf -0 orced wit h a com bin at ion of t h ese t w o colu m ns f orm ing a con cat enat ed Pages: 44 8

Below is samp le dat a for Calif or nia ( CA) and New Yor k ( NY) license nu mb er s f or t hr ee st ud en t s. a st u dent regist erin g m or e t h an on e v eh icle on camp us. As y ou can see, st u dent A104 has t w o r

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. STATE TAG_NO VEHICLE_DESC STUDENT_ID PARKING_STICKER Using t o- follow inst r uct ions an---------d ex am ples, --------------t his book pr esent s t echniq ues t o t ake ----- easy------------------adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CA CD 2348 1977 Mustang A103 C-101-AB-1 dat ab ases o incor1989 por at eGTI bu siness rA104 ules w hich arC-101-AB-2 e easy t o man age and m odif y as t he NY MH t8709 bu sin ess es. Topics cov er ed include: NY JRevolv 9837 1981 Civic A104 C-101-AB-3 in eg tconst aint the dict ion arcalled y We w View ill st or his inr for msatinion in dat a naew t able STUDENT_ VEHI CLES. We k now t h er e w ill b e int er est ( e. g ., vehicle r eg ist r at ion inf orm at ion) ; for now , w e'll j ust in clu de v eh icle d escr ip t ion, t h Com plex r ule enf orcem en t t he car , an d t he nu m ber of t he p ark ing st ick er issu ed by t he cam pus police. Th e key h er e is t h at can definit ely say t hat t he com binat ion of a st at e abbr eviat ion and licen se t ag n um ber is alw ays PL/ SQL p r ogr am un it s and langu age f eat u res ( STATE, TAG_NO) a concat enat ed pr im ary k ey. The DD L for t h is t able is: Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions CREATE TABLE student_vehicles (state Declar at iv e constVARCHAR2(2), r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch tag_no VARCHAR2(10), m or e vehicle_desc VARCHAR2(20), Pr ogr student_id am m ing Oracle Tr VARCHAR2(10), igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce VARCHAR2(10)) TABLESPACE student_data; forparking_sticker dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. ALTER TABLE student_vehicles [ Team LiB ] ADD CONSTRAINT pk_student_vehicles PRIMARY KEY (state, tag_no) USING INDEX TABLESPACE student_index;

Con cat enat [ Team LiB ed ] pr im ar y key s and seq uence- generat ed k ey s do not m ix. A sin gle colum n is all t hat seq uence- generat ed pr im ary key . This t ab le sh ould not in cor p orat e a seq uence; it st or es inf orm nat u r ally an d u niqu ely d ist ing uishes each v eh icle b y st at e and t ag nu mb er . Du ring y our in it ial desig n, y ou m ay be t old by y our client t hat cer t ain values w ill alw ay s be u niq say, for ex am ple w it h an inv ent or y sy st em , t h at t h e comb inat ion of COMPANY and PART_NO w il You go wit h t h is con cept and const r uct a concat enat ed p r im ar y k ey . Mont hs lat er , y ou lear n t hat except ions—som et im es t his is as m uch a r ev elat ion t o t he client as it is t o you . Your appr oach t h t ables and ad d a new colum n for t he seq uence. Som e m odeler s w ill, as a st an dar d pr act ice, m ak e ev ery pr imar y k ey a sequence- gener at ed colu t o a degr ee, discar ds realit y . For ex am ple, t h er e is no dou bt t hat a st at e abb r ev iat ion and a t ag w or ld , ar e un iq ue an d t ru ly can be used t o uniq uely id en t ify t h e at t r ibut es of an y vehicle on cam When t he de fact o st andar d in a pr oj ect is t o m ak e all pr im ary key s seq uence- g en er at ed, you ha at t ent ion t o how y ou quer y t he t able because y ou m ay f r eq uent ly qu er y t h e t able u sin g r eal- w or • Table of Content s abb rev iat ion an d t ag n um ber . These colu mn s m ight not hav e index es, u nless you specif ically cr e Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on w it h t he sequence has an in dex because it has a pr im ar y key ; h ow ev er, ot her colum ns m ay n ot By Kevines. Owens index

Pub lish er: Prent ice Hall PTR

3.1.7 Extra Indexes with Pseudo Keys Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

The STUDENT_VEHI CLES t ab le has a nat ur al p r im ar y k ey —it seem s nat u ral t o assum e t hat t he c Pages: 44 8 abb rev iat ion an d license num b er w ill alw ay s be u niqu e. Su ppose w e ad d a pseudo key , insist in g called VEHI CLE I D. We' ll m ak e VEHI CLE_I D t he pr im ary key . We t h en hav e t h e follow ing t able. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. CREATE TABLE student_vehicles Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake (vehicle_id NUMBER, adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our state VARCHAR2(2), dattag_no ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he VARCHAR2(10), bu vehicle_desc sin ess evolv es. Topics cov er ed include: VARCHAR2(20), student_id VARCHAR2(10), parking_sticker VARCHAR2(10)) TABLESPACE student_data; View in g const r aint s in t h e dat a dict ion ar y ALTER TABLE student_vehicles Com plex r ule enf orcem en t ADD CONSTRAINT pk_student_vehicles PRIMARY (vehicle_id) PL/ SQLKEY p r ogr am un it s and langu age f eat u res USING INDEX TABLESPACE student_index; Dat a t y pes and comp osit e st r u ct u re CREATE SEQUENCE student_vehicles_pk_seq; Er r or han dling and except ions Sup pose I nt erw-eprhav ocess e t he com sam muenicat samions ple dat a as Sect ion 3. 1 .6 , " Concat en at ed Pr im ar y Key . " Th e pr im VEHI CLE_I D, is a seq uence nu mb er t hat st art s wit h 1 . Aft er ad ding t hr ee v eh icles w e hav e t h e fo Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig enSTATE t , com plex dat abases. VEH_ID TAG_NO VEHICLE_DESC STUDENT_ID PARKING_STICKER ------ ----- -------- ------------ ---------- --------------[ Team1 LiB CA ] CD 2348 1977 Mustang A103 C-101-AB-1 2 NY MH 8709 1989 GTI A104 C-101-AB-2 3 NY JR 9837 1981 Civic A104 C-101-AB-3

[ Team The f ollow LiBin]g SQL quer ies t h e t able u sin g t h e pr im ary key colum n in t h e quer y . This q uery w ill u

SELECT * FROM student_vehicles WHERE vehicle_id = '1';

The ex ecu t ion p lan , show n her e, will in clud e t he in dex.

Execution Plan • Table of Content s ---------------------------------------------------------Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on 0 SELECT STATEMENT Optimizer=CHOOSE By 1 Kevin 0 Owens TABLE ACCESS (BY INDEX ROWID) OF 'STUDENT_VEHICLES' 2 1 INDEX (UNIQUE SCAN) OF 'PK_STUDENT_VEHICLES' (UNIQUE) Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

What ifI SBN: t he 0ap13plicat -0 850ion 33 -0 code r elies on t h e colu m ns f or st at e and license n um ber? This is a likely p inf ormPages: at ion 44 based on a st at e and license p lat e num ber could be dependent on field s select ed on 8 app licat ion developer could hav e used t he p rim ar y k ey , bu t chose t o use t h e ot her colum ns. The r et ur n t he sam e infor m at ion as t he p r ev ious select st at em ent . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. SELECT * Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake FROM students adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our WHERE state = 'CA' dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he AND tag_no = 'CD 2348'; bu sin ess evolv es. Topics cov er ed include: The dView iff er ence is t hat t he fir st er ya w ill ion likely in g const r aint s in t h equdat dict ar yr un f ast er . I f t her e ar e a signif ican t n um ber of st u w ill use t h e index of t he pr im ar y k ey. The second q uery w ill n ot u se an ind ex becau se t here is no STATE andplex TAG_NO. ex ecut Com r ule enfThe orcem en t ion plan show s a t able scan t h at w ill cause consider able w ait t im PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Execution Plan Er r or han dling and except ions ---------------------------------------------------------I SELECT nt er - pr ocess com mu Optimizer=CHOOSE nicat ions 0 STATEMENT 1 0 TABLE ACCESS (FULL) OF 'STUDENT_VEHICLES' Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e When a p seud o k ey is creat ed, as ear lier , an d t here is a nat ur al pr im ary key in t he t ab le, t here i Pr ogr amion m ing Oracle Trwigger s and Sts, or such ed Pr as oced ur es , an ThdirTAG d Ed itNO ionfr, om is an invm aluable r esou rce f or app licat developed ill t ake field STATE a for ( i. e., an HTML for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly and use t h ose field s t o quer y t he d at abase. When t his h appens, t h e per for m ance of t hat quer y is int plex abases. ar eellig t aken ent ,t ocom ident ify dat t hese t able scan s and r esolv e t hem w it h add it ion al ind ex es. [The Team LiB ] t o add a pseu do k ey is not being ju dged her e—t h e issu e is t o r ecognize w hen and i d ecision w hat ev er t hat key m ay be, is b ein g u sed and w hen it is n ot being used. Th er e ar e t h ree op t ions is not using t he sequ en ce p r im ar y k ey .

1 . Don 't use t he p seu do ind ex , VEHI CLE_ I D . I t p rov ides no benefit because t her e is a n at ur al [ Team LiB ] t he dat a: STATE an d TAG_NO. 2 . Cr eat e an index on t he colum n s STATE an d TAG_NO. 3 . Cr eat e a con cat enat ed UNI QUE const r ain t on colum ns STATE and TAG_ NO; t h e m er e cr eat const r ain t w ill enf or ce t he nat u r al business r ule t hat t h ese colum ns ar e u nique, p lu s creat e colum ns. Why wou ld som eone choose t o use a sequence r at her t h an colum n s t hat , in t h e r eal w orld, ident is a decision m ad e by t h e dat a m odeler . May be t he nat u r al pr im ary key is m any colum ns—f inan deal w it h fin ancial inst r um en t s and t r ading of t h ose in st ru ment s hav e so m any at t rib ut es t hat t h of a t able is m any colum ns. Th at doesn' t m ean t hose colu m ns can' t b e a p rim ar y k ey . An excess colum ns in a p rim ar y k ey m eans lar ge in dexes an d p ossible f or eign k eys t hat , if w e hav e ind ex e lar ger index es. Many colum ns in t he p r im ar y k ey may not be desirab le. •Secon dly , m Table Content s ayb e oft he m odeler has d oubt s as t o wh et her, in t h e fu t ur e, t hose colum ns w ill r emain Pr ogrusers am m ing Or at cl Tr ia gger StortehdeP roce s, Thir d cr Edi ti on end say h ee®dat is sunand iq ue; dat adure m odeler eat es

a pr im ary key only t o f in d out lat er t does, fact , cont ain du plicat es. So, r ev er t ing t o a concat enat ed pr imar y k ey m ay not be t h e fir By Kevinin Owens Sup pose you st ick w it h t he pseudo k ey , such as VEHI CLE_I D. Given t his ap pr oach , w e can st ill c r ulePub t hlish at ,er:w it hinicet he VEHI CLES t able, t h e STATE and TAG_NO ar e st ill uniqu e and y ou Prent HallSTUDENT_ PTR UNI Pub QUE r ainber t on ose colum ns. Th e UNI QUE const rain t d oes g en er at e an ind ex and con se Datconst e: Decem 0 5, t2h003 follow ing w ill hav e t he pot ent ial t o per for m at opt im al levels w it h t he u se of t he ind ex g en er at ed I SBN: 0- 13 -0 850 33 -0 const r ain t . Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow*ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d SELECT t eaches w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. FROM you student_vehicles WHERE state = 'CA' Using easyt o- follow inst2348'; r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake AND tag_no = 'CD adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sinDess evolv es.scen Topics er ed include: The DL for t he ario cov t o im plem en t t h e pseu do sequ en ce p lus a con cat en at ed un ique const r a TAG_ NO is t h e follow ing. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res CREATE TABLE student_vehicles (vehicle_id NUMBER, Dat a t y pes and comp osit e st r u ct u re state VARCHAR2(2), tag_no VARCHAR2(10), Er r or han dling and except ions vehicle_desc VARCHAR2(20), student_id VARCHAR2(10), I nt er - pr ocess com mu nicat ions parking_sticker VARCHAR2(10)) TABLESPACE student_data; Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch ALTERm TABLE student_vehicles or e ADD CONSTRAINT pk_student_vehicles Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce PRIMARY KEY (vehicle_id) forUSING dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly INDEX TABLESPACE student_index; int ellig en t , com plex dat abases. CREATE SEQUENCE student_vehicles_pk_seq; [ Team LiB ] ALTER TABLE student_vehicles ADD CONSTRAINT uk_student_vehicles_state_tag UNIQUE (state, tag_no)

USINGLiB INDEX TABLESPACE student_index; [ Team ] I f you d o not exp ect st at e and license nu m ber t o b e or r emain un iq ue, y ou can alw ays cr eat e a n t hese colum ns. So, r at her t h an add a u nique con st r aint as ear lier , r ep lace t hat w it h t h e follow ing an index .

CREATE INDEX student_vehicles_state_tag ON student_license(state, tag_no) TABLESPACE student_index;

•I n su mm ar y ,Table of Content s w hen you r appr oach t o p rim ar y k ey s is, by default , t o alw ay s use seq uence- genera Pr ogr am m ing a cl e ®qu Trer i gger Stor eAr d Peroce dure s,t Thir d es Edi ti consider howOryou y t hs eand t able. t her e at r ibut won it h in

t h e t able t o w hich a un iq ue const r a so, creat e a un iq ue const r aint . For all ot her colu m ns, look at h ow t h e t able is accessed an d ad d By Kevin Owens opt im ize per for m ance. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 3.1.8 Enable, Disable, and Drop I SBN: 0- 13 -0 850 33 -0 Pages: 44 8a pr imar y k ey const rain t w it h t he f ollow in g. You can d rop

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER

t eachesTABLE you w hat y ou n eed t o DROP kn ow CONSTRAINT t o build rob ust an d com plex dat ab ases f or y our b usiness. ; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our This rop s ttoheincor con por st r aint andsiness dr opsr ules t he ind ex associat it h t hat r ain t .y as t he dat abdases at e bu w hich ar e easyedt owman age const and m odif bu sin ess evolv es. Topics cov er ed include: Or acle w ill not allow you t o dr op a pr im ary key t o w hich t h er e is a r ef er encing for eign key . I f a t for eign k ey y ou w ill get t h is err or . View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res ORA-02273: this unique/primary key is referenced Dat aforeign t y pes andkeys comp osit e st r u ct u re by some Er r or han dling and except ions You can D ROP CASCADE t he con st raint . This w ill dr op t he pr im ar y k ey con st rain t and all f or eign I ntent er - pr ocess comnot mu rnicat t hat par . This does eq uirions e t hat t he f or eig n k ey const r ain t b e declar ed wit h t h e CASCADE alw ays dr op a pr im ary key w it h t he CASCADE opt ion, but it is p er m anent . The p rim ar y k ey an d Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch const r ain t s ar e delet ed f rom t he d at a d ict ionar y . The CASCADE opt ion is: m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. ALTER TABLE state_lookup [ Team LiB ] DROP CONSTRAINT state_lookup CASCADE;

You can check all r eferencing f oreign k ey s t o a p rim ar y k ey con st r aint w it h t he script MY_ CHI LD

5, Sect ion [ Team LiB5.]6 .5 . A less dr ast ic m easur e is t o disable a con st r aint . The CASCADE r est r ict ion app lies as well t o disa t her e ar e r ef erencing for eign k ey s, y ou can disable a pr imar y k ey con st rain t w it h:

ALTER TABLE state_lookup DISABLE CONSTRAINT state_lookup CASCADE;

A d isab led const r ain t is st ill d ef ined in t he dat a dict ion ary , it is ju st not being enfor ced. Fur t her m t o DI SABLED. Wit h t he CASCADE opt ion, t he st at us of t he pr im ar y key an d all ref er encing for eig set t o a DI SABLED st at u s. •

Table of Content s

Pr ogrin am m ingaft Orer a cl e i ggerys k and d rain P roce s, Thir d Edi on The dex, a®prTrimar ey Stor conest t dure is d isabled, isti gone—delet ed f rom t he d at a dict ionar y ; im mediat ely r ebuilt w h en t h e con st rain t is enabled. By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 SBN: 0- 13 -0 850 33 -0 ALTER I TABLE state_lookup ENABLE CONSTRAINT Pages: 44 8 pk_state_lookup;

This ALTER TABLE st at em ent r ecr eat es t he ind ex an d set s t h e pr im ary k ey const r ain t t o ENABLE const ain t screat ar e st t hese has t o be abled it h:st ems and dat ab ase ex per t Ef fectrively e ill andisabled. d man ageEach com of plex dat abases w iten h Or acle!w Sy Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our ALTER TABLE students fk_students_state; dat ab ases t o incor por at e ENABLE bu sinessCONSTRAINT r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: An index on a p rim ar y k ey colum n cannot be d r opped—it w ould be dr opp ed w it h a D ROP or DI S in gbe const r aint t h eafdat a dict y rain t w it h: I ndexView es can rebu ilt wsitin h no fect on tion h e ar const Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res a t y pes and comp osit e st rREBUILD; u ct u re ALTERDat INDEX pk_state_lookup Er r or han dling and except ions The ENABLE and DI SABLE k ey w or ds can be app en ded t o an y con st raint declarat ion . At t aching D I nt er - pr ocess com mu nicat ions const r ain t an d set s t h e st at e t o DI SABLED. I t can be enabled any t im e. The ENABLE key w ord is const r ain t clauses. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle TrOption igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce 3.1.9 Deferrable for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int enyt , kcom plex A pellig r im ar ey con st rdat aintabases. can be creat ed w it h t he opt ion DEFERRABLE. This op t ion perm it s an ap disable t h e const rain t d ur in g a load. Th e assu m pt ion is t hat man ipulat ion of t he t able w ill occu r, [ Team LiB ] com plet e t he d at a w ill conf orm t o t h e r ules of t he pr im ar y key const r aint . The app licat ion w ill CO dat a. At t h at COMMI T, t h e const r ain t is enf or ced. Should t he p rog r am hav e left in valid dat a in t h v iolat es t h e const r ain t —t he t ran sact ion is r olled back .

[ Team LiB ]

Scenario 1 Bad Data Is Loaded with Deferrable A st or ed pr ocedu re load s 1, 00 0 r ow s. Ther e ar e du plicat es. All 1 ,0 00 r ows are load ed . The p r og a com m it . The t ran sact ion is r olled back because t he dat a violat es t he con st r aint .

Scenario 2 Bad Data Is Loaded without Deferrable A st or ed pr ocedu re load s 10 00 row s. Th er e ar e du plicat es in t h is dat a. Th e pr ogr am p roceed s t o dat a and at som e p oin t a du plicat e is in ser t ed. Th e inser t fails. The ap plicat ion can ch oose t o ign • Table of Content s single inser t ( u sing ex cept ion han dling code) and cont in ue w it h t he r emain in g dat a. Th e pr ogr am Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on capable of r olling back t he t ran sact ion. By Kevin Owens

The D EFERRABLE opt ion is creat ed wit h t h e follow ing syn t ax—a samp le t able PARENT is cr eat ed Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

CREATE TABLE parent (parent_id NUMBER(2), parent_desc Ef fect ively creatVARCHAR2(10)); e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER parent pk_parent PRIMARY KEY t eachesTABLE you w hat y ou nADD eed CONSTRAINT t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. (parent_id) DEFERRABLE; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our The afases or emt ent ioned r ain t d ef init ionwishich t hear sam e as ttoh is next at ement : y as t he dat ab o incor porconst at e bu siness r ules e easy man agestand m odif bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y ALTERCom TABLE ADD CONSTRAINT pk_parent PRIMARY KEY plex parent r ule enf orcem en t (parent_id) DEFERRABLE INITIALLY DEFERRED; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a1 tis y pes and ositfollow e st r uinctgu re Scen ario sh ow n wcomp it h t he cod e. This PL/ SQL b lock load s dup licat e d at a. Af t er t he lo COMMI T, a d uplicat e is DELETED. Th is block com plet es w it h su ccess becau se t he d uplicat e w as r Er r. or han dling and except ions com mit I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e DECLARE Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce BEGIN for dat abase d IMMEDIATE ev elopers, d 'SET esign er s, and pr oj ectALL leader s look in g t o b uild an d m aint ain t r uly EXECUTE CONSTRAINTS DEFERRED'; int ellig en t , com plex dat abases. INSERT [ Team LiB ] INSERT INSERT INSERT

INTO INTO INTO INTO

parent parent parent parent

values values values values

(1,'A'); (1,'B'); (3,'C'); (4,'D');

DELETE [ Team LiB ] FROM parent WHERE parent_desc = 'B'; COMMIT; END;

I f t his b lock h ad n ot r em oved t he d uplicat e, an Or acle er ror w ould occur . Th at er ror is t he sam e k ey con st r aint v iolat ion . The f ollow in g b lock accom plish es t he sam e t ask, load ing t he sam e dat a not use t h e defer rab le opt ion. Rat her , all g ood d at a r emain s in t he PARENT t able.

BEGIN BEGIN INSERT INTO parent values (1, 'A'); • Table WHEN of Content s EXCEPTION DUP_VAL_ON_INDEX THEN null; Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on END; BEGIN By Kevin Owens INSERT INTO parent values (1, 'B'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN null; Pub END; lish er: Prent ice Hall PTR BEGIN Pub Dat e: Decem ber 0 5, 2 003 INSERT INTO I SBN: 0- 13 -0 850 33 -0 parent values (3, 'C'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN null; Pages: 44 8 END; BEGIN INSERT INTO parent values (4, 'D'); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN null; Ef fectEND; ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. COMMIT; END; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he The d at a r em ain ing in t he t able is t he f ir st , t h ird , and f our t h row . Th e DEFERRABLE opt ion loads bu sin ess evolv es. Topics cov er ed include: const r ain t is ap plied an d t h e t r ansact ion is com m it t ed or rolled b ack . Th e second scen ario pr ovid back a dup licat e inser t . Alt ern at ively , t he ap plicat ion can sk ip t he d uplicat e insert and cont inu e p View in g const r aint s in t h e dat a dict ion ar y The d ef err able op t ion sh ould not b e used t o per m it t h e t able t o be a w ork ar ea. Scenar io 1 seem app licat ionplex t o load anden t hen m anipulat e t hat dat a, cleaning out bogu s r ecor ds. Hopef ully, t Com r ule dat enf a, orcem t up on a comm it . Alt er nat iv es ex ist . Temp or ary t ables can be cr eat ed f or loading d at a f or m anipu m anipu ion pan d cleansin of t he dat a, t he r ow s ar e inser t ed int o t he p r oduct ion t able. Temp or PL/lat SQL r ogr am un it gs and langu age f eat u res for t he life of a session or t r ansact ion . The f ollow in g D DL creat es a t em por ar y t able t hat can be m em or y at ab t hat f oret he uruat Dat t yle pes andpersist compsosit st r udct reion of a t r ansact ion. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e TEMPORARY const r aint s, TABLE including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch CREATE GLOBAL m or e parent_temp (parent_id NUMBER(2), Prparent_desc ogr am m ing Oracle Tr igger s andONSt or ed Pr oced ur es ,ROWS; Th ir d Ed it ion , is an inv aluable r esou rce VARCHAR2(10)) COMMIT DELETE for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. Scen ario 1 can now use t he t em por ar y t ab le for m assaging t he r aw dat a. Wh en d at a is m ov ed in [t able, Teamt hLiB ] e comm it delet es r ow s fr om t he t em por ar y t able. The t em por ar y t able is p r iv at e t o t his follow ing PL/ SQL b lock is Scenar io 1 using a t em p orar y t ab le w it h n o def er r able opt ion .

[ Team LiB ] BEGIN INSERT INSERT INSERT INSERT

INTO INTO INTO INTO

parent_temp parent_temp parent_temp parent_temp

values values values values

(1,'A'); (1,'B'); (3,'C'); (4,'D');

DELETE FROM parent_temp WHERE parent_desc = 'B'; INSERT INTO parent SELECT * FROM parent_temp; COMMIT; END;

ion en •The D EFERRABLE Table ofopt Content s for ces t he const r aint wit h each D ML st at em ent . This is t he default be const r ain t w Or it haout hei gger DEFERRABLE t ion; hs, owThir ev der,Edit tihe Pr ogr am m ing cl e ® t Tr s and Stor e d op P roce dure onD EFERRABLE does pr ovid e for t he f ollo By Kevin Owens

An applicat ion can SET CONSTRAI NTS ALL DEFERRED, load d at a, and h ave t h e const r ain t e t r ansact ion com plet es w it h a COMMI T st at ement . Pub lish er: Prent ice Hall PTR Pub Dat con e: Decem ber 0can 5, 2 003 The st r aint be

disabled w it h an ALTER TABLE st at em en t t o DI SABLE t he con st r aint . The con aint can I SBN: 0- st 13r-0 850 33 -0 b e enabled wit h NOVALI D ATE, leavin g d uplicat es in t h e t able b ut en for c fuPages: t ur e 44 DML ( see Sect ion 3. 1 .1 0, " NOVALI DATE. " ) 8

The D EFERRABLE opt ion can b e declar ed wit h t h e follow ing at t r ibut e: Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. DEFERRABLE INITIALLY DEFERRED Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ases t o incor por at e bu siness r ules wshich ar e easy tthe o man age andonly m odif Theab I NI TI ALLY DEFERRED feat u re default t o enf orcing con st r aint w hyenasat the ran sact ion co bu sin ess evolv es. Topics cov er ed include: set , each DML st at em en t is n ot ind ividu ally en for ced . Enf or cem ent t akes p lace on ly wh en t h e t r a This op t ion p r ovides t h e follow ing: View in g const r aint s in t h e dat a dict ion ar y An applicat ion begins a t r ansact ion k now ing t hat t he con st r aint is enf orced u pon t he com m Com plex r ule enf orcem en t loads d at a, t h en com mit s. Th e en t ire t r ansact ion is accep t ed or r eject ed . The cod e con t ains and a COMMI T. There is not hing in t he cod e t o r eflect t hat t h e I NSERTS ar e v alidat ed only PL/ SQL p r ogr am un it s and langu age f eat u res a com m it , t he applicat ion can specif ically check for v alidat ion w it h t he f ollow ing . Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions EXECUTE IMMEDIATE 'SETions CONSTRAINTS ALL IMMEDIATE'; I nt er - pr ocess com mu nicat Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch The f ollow m or ein g su mm ar izes DEFERRABLE opt ion. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce You can ddev eclar e t he dconst w hich h asint he f ollow g at t rib ut es he d at a for1 .dat abase elopers, esignr aint er s, DEFERRABLE, and pr oj ect leader s look g to b uildinan dm aint ainint rtuly USER_CONSTRAI NTS v iew . int ellig en t , com plex dat abases. DEFERRABLE = DEFERRABLE [ Team LiB ] DEFERRED = I MMEDI ATE This op t ion m eans t hat t he const r aint is en for ced w it h each DML. You can w r it e code, as sh

dir LiB ect s] Or acle t o r ef r ain f r om const rain t enf orcem en t u nt il a COMMI T or a ROLLBACK. Th is [ Team CONSTRAI NTS st at em ent in y our cod e. 2 . You can d eclar e t he const r aint w it h t he opt ion DEFERRABLE I NI TI ALLY DEFERRED. This set dat a dict ionar y t o: DEFERRABLE = DEFERRABLE DEFERRED = DEFERRED 3 . This op t ion m eans t hat t he def ault b eh avior f or a t ran sact ion is t o en for ce con st rain t s w hen a COMMI T or ROLLBACK. A PL/ SQL p r ogr am w ould look lik e an y ot her pr og ram wit h t h is op t o look in t o t h e st at us of t he const r ain t t o see wh en t h e const rain t is enf or ced. An ap plicat i enfor ce const r aint s w it h t he SET CONSTRAI NTS ALL I MMEDI ATE com m and. Wit hout t his st const r ain t w ill b e en for ced w hen t he t ran sact ion comp let es. • 4.

You canTable ALTER t he DsEFERRED st at u s of a const r aint . I f y ou declar e it as DEFERRABLE, t hen of Content

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

DEFERRABLE = DEFERRABLE

By Kevin Owens

DEFERRED = I MMEDI ATE Pub lish er: Prent Halle PTR You can exice ecut t he

f ollow ing :

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

ALTER TABLE table_name MODIFY CONSTRAINT Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t constraint_name INITIALLY DEFERRED. Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. This chan ges t he st at e t o: Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our DEFERRABLE = DEFERRABLE dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: DEFERRED = DEFERRED Viewcan in g const r aint t h e dat astdict aray const r aint declar ed I NI TI ALLY DEFERED w it h t he 5 . You ALTER t hesDinEFERRED at uion s of Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re ALTER TABLE table_name MODIFY CONSTRAINT Er r or han dling and except ions constraint_name INITIALLY IMMEDIATE. I nt er - pr ocess com mu nicat ions ges t hes,stincluding at e t o: DeclarThis at iv chan e const r aint p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e DEFERRABLE = DEFERRABLE Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce DEFERRED = I MMEDI ATE for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. As alw ay s, you can disab le t he const r aint and t hen en able it wit h ALTER TABLE com m and s. [ Team LiB ]

3.1.10 NOVALIDATE

The NOVALI [ Team LiB ]DATE opt ion allow s nonconf orm ing d at a t o be loaded and lef t in t h e t able w hile t h e r is enabled only for fu t ur e inser t s. Th is opt ion can b e used in dat a w arehou se sy st ems wh er e m an hist or ical dat a for an aly sis. Hist or ical dat a w ill fr equent ly v iolat e pr esen t day business ru les. To load non com p lian t d at a, t he con st r aint m ust b e init ially cr eat ed w it h t he defer rab le opt ion. Pr hist or ical dat a, t h e const r ain t m ust be d isabled. The f ollow ing cr eat es a t able w it h a d ef er r able p const r ain t . Pr ior t o t he load, t he const r aint is disabled . Aft er w ar d, t h e const r ain t is enab led w it h opt ion . From t his poin t f orw ar d, t he h ist or ical dat a r em ains b ut all new insert s w ill be const r aine pr im ary key .

CREATE TABLE parent (parent_id NUMBER(2), • parent_desc Table of Content s VARCHAR2(10)); Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

ALTER TABLE parent ADD CONSTRAINT pk_parent PRIMARY KEY By Kevin Owens (parent_id) DEFERRABLE; ALTER Pub lish TABLE er: Prent parent ice Hall PTR DISABLE CONSTRAINT pk_parent; Pub Dat e: Decem ber 0 5, 2 003

BEGIN I SBN: 0- 13 -0 850 33 -0 INSERT INTO parent values (1,'A'); Pages: 44 8 INSERT INTO parent values (1,'B'); INSERT INTO parent values (3,'C'); INSERT INTO parent values (4,'D'); END; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin ens ex plor es PL/ SQL, Or acle's answCONSTRAINT er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER Ow TABLE parent ENABLE NOVALIDATE pk_parent; t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Aft er t he af orem en t ioned PL/ SQL block execut es, du plicat es ex ist in t he t ab les; h ow ev er, all new adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our t o t he p rim ar y k ey . dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

3.1.11 Error Handling in PL/SQL View in g const r aint s in t h e dat a dict ion ar y A d uplicat e insert in PL/ SQL is easily capt ur ed w it h t he PL/ SQL built - in except ion. The except ion Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re DUP_VAL_ON_INDEX Er r or han dling and except ions I nt er - pr ocess com mu nicat ions I ncluding an except ion han dler will allow an ap plicat ion t o hand le t he r ar e case of a du plicat e. T pr oced ur e r et a Boolean, indicat ingparim f ailur if t,he insert fis dupklicat Declar at ur iv ensconst r aint s, including ar y ek ey u nique, or aeign ey, e. ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. CREATE OR REPLACE FUNCTION [ Team LiBinsert_parent ] (v_id NUMBER, v_desc VARCHAR2) RETURN BOOLEAN IS BEGIN

INSERT [ Team LiB ] INTO parent VALUES (v_id, v_desc); return TRUE; EXCEPTION WHEN DUP_VAL_ON_INDEX THEN return FALSE; END;

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

3.2 UNIQUE I n t his sect ion w e use a t able t h at st or es st u dent infor m at ion. Th e t able d escr ip t ion is:

Name Null? Type ------------------------------ -------- -----------STUDENT_ID VARCHAR2(10) •STUDENT_NAME Table of Content s VARCHAR2(30) Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on COLLEGE_MAJOR VARCHAR2(15) STATUS VARCHAR2(15) By Kevin Owens STATE VARCHAR2(2) LICENSE_NO VARCHAR2(30) Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

The UNI QUE const r aint is applied t o a colu mn , or set of colum ns, t o en for ce t he follow in g I SBN: 0- 13 -0 850 33 -0 r ule: I f a v alue ex ist s, t han t hat valu e mu st be uniqu e. Pages: 44 8

This d ef init ion sou nds sim ilar t o a PRI MARY KEY con st r aint . The f ollow ing is a com p arison bet w een t h e pr imar y k ey and un ique const r aint s. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t t able h ave justSQL, one Or pr im ar y answ key const but a ur t able can h ave mor e t h( SQL) an one KevinAOw ens can ex plor es PL/ acle's er t or aint t h e St r uct ed Query Langu age , an d un iq ue w const t eaches you hat ryaint ou n. eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. colum n follow t hat isinst parr tuct ofions a pr an im darex y key can never h avepraesent NULL e. Aues colum n t hat is UsingAeasyt oam ples, t his book s tvalu echniq t o t ake par unacle iquefeat const r aint can null. a colum n has a unurique const r aint , t here adv ant agt eofofaOr ur es such asbterig gersI fand st ored pr oced es- f eat u r es t hat allowcan y our m an r owspor wit f orr ules t h at wcolum n. eTh e v alu t hat notm null ustt he be u nique. dat abbe ases t o yincor athe abuNULL siness hich ar easy t o es man ageare and odif ymas bu sin ess evolv es. Topics cov er ed include: When w e creat e a pr im ary key w e cr eat e or r eu se an ind ex . Th e same is t ru e for UNI QUE const r ain t s. View in g const r aint s in t h e dat a dict ion ar y The p r im ar y k ey and uniq ue const r aint colum ns can be t he p arent in a f oreign k ey rCom elat plex ion shrip . The colum en n st of a f oreign k ey con st r aint fr equ en t ly ref er b ack t o colum ns of ule enf orcem a p r im ar y k ey con st raint . They can also refer b ack t o colum ns of a uniq ue const r aint . PL/ SQL p r ogr am un it s and langu age f eat u res The f ollow in g D DL creat es a concat enat ed un iq ue const r aint on colum ns ( A, B) : Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions CREATE TABLE temp (pk NUMBER PRIMARY KEY, a NUMBER, b NUMBER); at ivtemp e const r aint s, including uk_temp_a_b p rim ar y k ey , uUNIQUE nique, f (a, or eign k ey, ch eck , and m uch ALTERDeclar TABLE ADD CONSTRAINT b); m or e Pr ogr am and nStpr orov edided Pr oced es a , Th ir d does Ed it ion , isqualif an inv aluable r esou rce NULLs arm e ing p er Oracle m it t ed Tr in igger any scolum t heurdat t hat ex ist ies as u niqu e. The for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly follow ing I NSERT st at em ent s ar e v alid. int ellig en t , com plex dat abases. [ Team LiB ]

-- UNIQUE Constraint on last 2 columns.

INSERT [ Team INSERT INSERT INSERT INSERT INSERT INSERT INSERT

INTO LiB ] INTO INTO INTO INTO INTO INTO INTO

temp temp temp temp temp temp temp temp

VALUES VALUES VALUES VALUES VALUES VALUES VALUES VALUES

(1, 1, 1); (2, 2, 1); (3, 1, 2); (4, NULL, NULL); (5, NULL, NULL); (6, 1, NULL); (7, NULL, 1); (8, 2, NULL);

The f ollow in g d uplicat es t he last in ser t and raises a const r aint violat ion.

•SQL> insert Table of Content into temp svalues (9, 2, NULL); Pr ogr am minto ing Or atemp cl e ® Trvalues i gger s and Stor2, e d PNULL) roce dure s, Thir d Edi ti on insert (9,

* Kevin Owens By ORA-00001: unique constraint (SCOTT.UK_TEMP_A_B) violated Pub lish er: Prent ice Hall PTR

Not ice t hat he p ref and a m inu s 1 for t h e err or code are id en t ical t o t h e pr im ary key Pub Dat e: tDecem ber ix 0 5," 2ORA" 003 const r ain t v0iolat I SBN: 13 -0ion. 850 33 -0 Pages: 44 8

3.2.1 Combining NOT NULL, CHECK with UNIQUE Constraints A fect Ef NOTively NULL creat const e an rain d tman is som ageetcom im es plex adddat edabases t o t he UNI w it hQUE Or acle! constSy r aint st ems . This andadd datitab ionase al ex per t rKevin eq uir em Owent ens st exipplor ulates esPL/ t hat SQL, t he Or colum acle's n vansw alues er mt oust the b eStuniqu r uct ure ed and Query t h at NULLs Langu age are (nSQL) ot , an d t eaches allow ed . you Thewf ollow hat yin oug nillust eed rt at o es kn ow t hist ocase. build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: CREATE TABLE temp (pk NUMBER PRIMARY KEY, a NUMBER NOT NULL); ALTER TABLE temp ADD CONSTRAINT uk_temp_a UNIQUE (a); View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enfconst orcem en t s ar e of t en sup plement ed w it h a CHECK const r aint t hat Con cat enat ed un ique r aint pr event s t he cond it ion: on e colu m n is NULL and on e colu mn h as a v alue. This is enf or ced r ogr followPL/ ingSQL t hispex amam ple.un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions CREATE TABLE temp (pk NUMBER PRIMARY KEY, a NUMBER, b NUMBER); ALTERDeclar TABLE ADD CONSTRAINT b); at ivtemp e const r aint s, including uk_temp_a_b p rim ar y k ey , uUNIQUE nique, f (a, or eign k ey, ch eck , and m uch ALTERm TABLE temp ADD CONSTRAINT ck_temp_a_b CHECK or e ((a IS NULL AND B IS NULL) OR (amIS NULL AND sband IS StNOT Pr ogr am ing NOT Oracle Tr igger or edNULL)); Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. The af or em ent ioned CHECK an d UNI QUE const r aint com bin at ion allow s t h e fir st t w o in ser t s, bu t r eject s t]he second t w o inser t s. [ Team LiB

[ Team INSERT INSERT INSERT INSERT

LiB ] INTO INTO INTO INTO

temp temp temp temp

VALUES VALUES VALUES VALUES

(6, 1, 1); (7, NULL, NULL); (6, 1, NULL); (7, NULL, 1);

-----

successful successful fails fails

Com bin in g NOT NULL and CHECK const r aint s w it h UNI QUE const r ain t s allow s for sev er al opt ion s. The colum n v alu es, w h en dat a is pr esen t , m ust b e un iq ue. This is enf or ced w it h t he UNI QUE const r ain t . Any colum n or all colum ns in t h e UNI QUE con st raint can be m and at ory wit h NOT NULL const r ain t s on indiv idual colu mn s. •

Table of Content s

Com binOrataions ofi gger NULL andStor NOT r est ict ions can Pr ogr am m ing cl e ® Tr s and e d PNULL roce dure s, rThir d Edi ti on

be ap plied using a CHECK

const r ain t an d Boolean logic t o dict at e t he r u le.

By Kevin Owens

Pub lish er: Prent ice Hall PTR 3.2.2 Students Table Example Pub Dat e: Decem ber 0 5, 2 003 I SBN: 13 -0 850 33 -0 Con sider a t0able, STUDENTS, t hat in clud es colu mn s for st u dent dr iver 's license infor m at ion. Not evPages: ery st44 u dent has a license—t his has t o be con sider ed. Ou r r ules ar e: 8

Ev ery st u dent mu st hav e a uniq ue ident if icat ion nu mb er or, STUDENT_I D—t h is is t he pr im ary key . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t KevinI fOw esaPL/ SQL, acle's t answ er t oen t hat e ion St r uct ed Query ( SQL) , an d a ens st udex enplor t h as d riv er' s Or license h e concat of ur license num Langu b er anage d st at e t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. abb rev iat ion m ust be u nique. Th e colu m ns f or st at e and license ar e n ot m and at ory and do not hav e a NOT NULL con st rain t . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag ef inal of Or acle feat such as tes rig tgers and st ored pren oced es-af eat u r es tthat allow y our The CHECK conurstes raint ensur hat should a st ud t h ur ave license, h e st at e and dat ablicense ases t o vincor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he alues ar e bot h ent er ed int o t he sy st em . bu sin ess evolv es. Topics cov er ed include: The f ollow in g D DL creat es t he STUDENTS t able w it h a con cat enat ed UNI QUE const r ain t on STATE and LI CENSE_NO. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res CREATE DatTABLE a t y pesstudents and comp osit e st r u ct u re (student_id VARCHAR2(10) NOT NULL, student_name Er r or han dlingVARCHAR2(30) and except ionsNOT NULL, college_major VARCHAR2(15) NOT NULL, status I nt er - pr ocess VARCHAR2(15) com mu nicat ionsNOT NULL, state VARCHAR2(2), license_no Declar at iv e const VARCHAR2(30)) r aint s, including TABLESPACE p rim ar y k ey student_data; , u nique, f or eign k ey, ch eck , and m uch m or e ALTER TABLE students Pr ogr m ing Oracle pk_students Tr igger s and St or ed Pr oced es , Th ir d Ed it ion , is an inv aluable r esou rce ADDamCONSTRAINT PRIMARY KEYur(student_id) forUSING dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly INDEX TABLESPACE student_index; int ellig en t , com plex dat abases. ALTER TABLE students [ Team LiB ] ADD CONSTRAINT uk_students_license UNIQUE (state, license_no) USING INDEX TABLESPACE student_index;

ALTER [ Team TABLE LiB ] students ADD CONSTRAINT ck_students_st_lic CHECK ((state IS NULL AND license_no IS NULL) OR (state IS NOT NULL AND license_no is NOT NULL));

The f ollow in g p ar agr aphs su mm ar ize k ey p oint s ab out t he abov e DD L. We call t h e pr imar y k ey const r ain t PRI MARY KEY. The u nique con st r aint is j ust " UNI QUE." I n conv er sat ion w e of t en r efer t o " uniq ue k ey " con st r aint s, but w hen w r it ing DDL, leave of f t he " KEY" p ar t . Also, uniq ue const r ain t s ar e of t en nam ed w it h a pr efix of " UK." The p r im ar y k ey , f or eig n k ey, and uniq ue const r aint all wor k t oget her t o enf or ce r ef erent ial in t egr it y. But t he DD L sy nt ax f or a uniqu e const r ain t d oes n ot in clud e t he " KEY" k ey w or d. Table of Content The u niqu e con st rainst causes an in dex t o be creat ed; t her ef or e, we hav e included t he t h ese colum ns has alr ead y been creat ed, t hen t he const r aint w ill u se t hat in dex) . For all t he D DL in t his t ext , t he t ables By Kevin Owens ar e creat ed in a STUD ENTS_DATA t ablesp ace and all index es are cr eat ed in a STUDENTS_I NDEX t ablespace—a fair ly st and ard pr act ice. •

Pr ogr am m ing Or a cl eas ® Tr s and P roce Edi ex ti onon t ablespace t hiegger locat ionStor fore dt his inddure ex s,( ifThir and ind

Pub lish er: Prent ice Hall PTR

The u niqu e con st rain t is n amed UK_ STUDENTS_LI CENSE. Con st rain t nam es ar e lim it ed t o 30 ch ar act er s. Const r aint nam es in t his t ext ar e pr eceded w it h a pr efix t o indicat e t h e I SBN: 0- 13 -0 850 33 -0 const r ain t t yp e. Th is is follow ed b y t he t able nam e. For a p rim ar y k ey con st r aint , t hat is Pages: 8 all w e 44 n eed. For ot her con st rain t s, w e t r y t o ap pend t he colum n nam e—t his can be dif ficult b ecause t ab le nam es and colu m n n am es m ay b e up t o 30 ch aract er s. Som et im es y ou mu st abb rev iat e. Most im por t ant , t he n ame of t he const r aint sh ould clear ly indicat e t h e const r ain t t y pe and t able. The colum n nam es included in t he Ef fectconst ively rcreat e an be d man com dat abases w itroach h Or acle! ems and in dat ain t can shorage t abbr evplex iat ion s—t his app helpsSy wst hen r esolv g ab anase ex per t Kevinapp Owlicat ens ion ex plor es rain PL/ SQL, Orion. acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d const t v iolat t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Pub Dat e: Decem ber 0 5, 2 003

Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 3.2.3 Deferrable and Options adv ant ag e of Or acle feat ur esNOVALIDATE such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he Sim ilar pr imes. ar yTopics key const a UNI QUE con st r aint can be declared as defer r able. The bu sin esst oevolv cov reraint ed s, include: const r ain t can be d isab led and enabled w it h ALTER TABLE st at em ent s. All t he opt ion s descr ibed in Sect ion 3. 1 .9 , " D ef er r able Opt ion, " an d 3. 1. 1 0, " NOVALI DATE, " ar e ap plicab le t o Viewconst in g const r aint s in t h e dat a dict ion ar y UNI QUE r ain t s. Com plex r ule enf orcem en t

3.2.4PL/Error SQL p rHandling ogr am un it s in andPL/SQL langu age f eat u res Dat a et yinsert pes and osit e stkey r u ctand u re u nique con st r aint , is capt ur ed wit h t h e PL/ SQL b uilt A d uplicat , forcomp a pr im ary in ex cep t ion. Th e ex cept ion nam e is Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e DUP_VAL_ON_INDEX Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly The f ollow in g p r ocedu re in ser t s a st u dent and capt ur es un iq ue const r aint er r or s. The code f or int ellig en t , com plex dat abases. a ch eck const r aint er r or is also capt ur ed. The check con st r aint err or n um ber is m app ed t o a declared ex cept ion. Th e pr oced ur e t hen includes a hand ler f or t hat except ion. The p rim ar y [ Team LiB ] k ey and uniqu e const r ain t er r ors h ave t he p redefin ed except ion declared in t he langu age. Ot h er t yp es of er r or s, su ch as check const r ain t er ror s, n eed ex cep t ions d eclar ed t h at m ust be m apped t o t he Or acle err or n um ber. The check const rain t er ror num ber is m inu s 22 90.

[ Team LiB ]

CREATE OR REPLACE PROCEDURE insert_student(v_student_id VARCHAR2, v_student_name VARCHAR2, v_college_major VARCHAR2, v_status VARCHAR2, v_state VARCHAR2, v_license_no VARCHAR2) IS check_constraint_violation exception; pragma exception_init(check_constraint_violation, -2290); BEGIN INSERT INTO students VALUES • Table of Content s v_student_name, (v_student_id, Pr ogr am m ingv_college_major, Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on v_status, v_state, v_license_no); By Kevin Owens dbms_output.put_line('insert complete'); EXCEPTION Pub lish er: Prent ice Hall PTR WHEN THEN Pub Dat e:DUP_VAL_ON_INDEX Decem ber 0 5, 2 003 dbms_output.put_line('PK or unique const violation'); I SBN: 0- 13 -0 850 33 -0 WHEN check_constraint_violation THEN Pages: 44 8 dbms_output.put_line('check constraint violation'); END;

Ef fect ively an d lin man ageic,com dat abases w it h Or acle! st emseand ab ase To t est t he creat er rore hand g log u seplex SQL* Plu s t o EXECUTE t he pSy rocedur w it hdat som e datex a.per Thte Kevin Owinser ens ex PL/ SQL, answ er t o vt hiolat e Ster uct ed Query fir st t wo t s plor fail es because t h eOrstacle's at e and license t heurcheck constLangu r aint rage u le:( SQL) bot h ,aran ed tNULL eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. or bot h ar e NOT NULL. Using easyinst r uct ionsk .an d ex aminser ples, t t fails his book pr esent t echniq ues t o t ake The t hir d antdo-ffollow our t h inser t s wor The last because it v siolat es t he u niqu e adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat allow y our const r ain t , w hich is a d uplicat e of t he p r ior in ser t . dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y insert_student('A900','Ann','Math','Degree','CA',NULL); plex r ule enf orcem en t checkCom constraint violation PL/ SQL p r ogr am un it s and langu age f eat u res insert_student('A900','Ann','Math','Degree',NULL,'ABC'); checkDat constraint a t y pes and violation comp osit e st r u ct u re insert_student('A900','Ann','Math','Degree',NULL,NULL); Er r or han dling and except ions insert complete I nt er - pr ocess com mu nicat ions insert_student('A902','Joe','Math','Degree','CA','ABC'); insert Declar complete at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e insert_student('A903','Ben','Math','Degree','CA','ABC'); Pr m ing Oracle igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce PKogr oramunique constTr violation for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] [ Team LiB ]

[ Team LiB ]

3.3 Foreign Key Foreign k ey con st r aint s en for ce r ef er ent ial in t eg r it y . A for eign key const r aint rest r ict s t he dom ain of a colum n valu e. An ex amp le is t o r est rict a STATE abbr ev iat ion t o a lim it ed set of v alues in an ot her cont r ol st r uct ur e—t hat being a p arent t ab le. The t er m " look up " is of t en u sed w hen r efer r in g t o t ab les t h at p rov ide t his t y pe of r eference inf orm at ion. I n som e app licat ions, t h ese t ab les ar e cr eat ed w it h t his k eyw or d—a pr act ice w e'll u se h er e w it h t he ex am ple STATE_ LOOKUP. St ar t w it h cr eat in g a looku p t able t hat pr ov ides a com plet e list of st at e abb rev iat ion s. Then intof egr it y t os en su re t hat st u dent s h ave valid st at e abbr ev iat ion s. The f irst t able •use r efer en t ial Table Content is ogr t heamstmating e looku able h STATE t he prs, imThir aryd key Pr Or a cl ep ® tTr i ggerwsitand Stor e d as P roce dure Edi ti.on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

CREATE TABLE state_lookup I SBN: 0- 13 -0 850 33 -0 (state VARCHAR2(2), Pages: 44 8 VARCHAR2(30)) TABLESPACE student_data; state_desc ALTER TABLE state_lookup ADD CONSTRAINT pk_state_lookup PRIMARY KEY (state) USING Ef fect ivelyINDEX creat eTABLESPACE an d man age student_index; com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. To in ser t a few r ow s: Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: INSERT INTO state_lookup VALUES ('CA', 'California'); View in g const r aint s in t h e dat a dict ion ar y 'New York'); INSERT INTO state_lookup VALUES ('NY', INSERT INTO state_lookup VALUES ('NC', 'North Carolina'); Com plex r ule enf orcem en t PL/ p r ogr s and eating u res We enf orSQL ce r efer enam t ial un intitegr it y blangu y impage lem fent t he par en t –child relat ionship, gr aphically show n in Figur e 3- 2 . Dat a t y pes and comp osit e st r u ct u re

Figu e 3 - 2ions . For e ign Er r or han dling andr except

Key w it h St at e Looku p.

I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] Figur e 3- 2 sh ows a one- t o- m any relat ionship bet w een t he STATE_LOOKUP t ab le and t he STUDENTS t able. The STATE_ LOOKUP t able def in es t he " u niver sal set " of st at e abb rev iat ions—each st at e being r ep r esent ed once in t h at t able; hence, a p rim ar y k ey on t h e

STATE [ Team colu LiB mn ] of STATE_ LOOKUP. A st at e fr om t h e STATE_LOOKUP t ab le can app ear mu lt iple t im es in t h e STUD ENTS t ab le. Ther e can b e m any st ud en t s fr om a single st at e. Hence r ef erent ial in t egr it y imp lem ent s a one- t o- m any relat ionship bet w een STATE_ LOOKUP an d STUDENTS. The f or eig n k ey also ensur es t he int egr it y of t h e STATE colu mn in t he STUDENTS t able—a st udent w it h a d riv er ' s license w ill alw ay s hav e a st at e ab br eviat ion t hat is a m em ber of t he STATE_ LOOKUP t able. The f or eig n k ey const r ain t is cr eat ed on t he ch ild t able. Followin g is t he STUDENTS t able w it h a f or eig n k ey const r ain t . Wit h an ALTER TABLE st at em en t , w e declare t he colum n STATE t o hav e a for eig n key const r aint t hat r efer ences t he pr im ar y key colum n of t he STATE_ LOOKUP t able.

Scr ipt 3 -1Table For ei gn Ke y w it h St a t e Look u p D DL. • of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE TABLE students (student_id VARCHAR2(10) NOT NULL, student_name VARCHAR2(30) NOT NULL, Pub lish er: Prent ice Hall PTR college_major VARCHAR2(15) NOT NULL, Pub Dat e: Decem ber VARCHAR2(20) 0 5, 2 003 status NOT NULL, I SBN: 013 -0 850 33 -0 state VARCHAR2(2), license_no Pages: 44 8 VARCHAR2(30)) TABLESPACE student_data; ALTER TABLE students ADD CONSTRAINT pk_students PRIMARY KEY (student_id) USING Ef fect ivelyINDEX creat eTABLESPACE an d man age student_index; com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER students t eachesTABLE you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ADD CONSTRAINT uk_students_license UNIQUE Using easy-(state, t o- follow license_no) inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake USING TABLESPACE student_index; adv ant ag eINDEX of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he ALTER TABLE bu sin ess evolv students es. Topics cov er ed include: ADD CONSTRAINT ck_students_st_lic CHECK ((state IS NULL AND license_no IS NULL) OR View in g(state const r aint in t hNULL e dat AND a dictlicense_no ion ar y IS sNOT is NOT NULL)); plex students r ule enf orcem en t ALTERCom TABLE ADD CONSTRAINT fk_students_state PL/ SQLKEY p r ogr am un it sREFERENCES and langu age f eat u res FOREIGN (state) state_lookup (state); Dat a t y pes and comp osit e st r u ct u re The D DL scr ipt in Scrip t 3 - 1 cr eat es t he STUDENTS t able and t ab le con st rain t s. These Er r or han dling and except ions const r ain t s enf orce t h e follow ing r ules: I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] Ru le

Enf orced W it h

A st u dent is uniqu ely id en t if ied b y a STUDENT_ I D .

PRI MARY KEY con st rain t .

A st u dent MAY hav e a dr iver 's license. I f t h ey do, t h at st at e an d license com binat ion is un ique am ong all ot her st udent s.

UNI QUE const r ain t on STATE and LI CENSE.

I f STATE is NULL t h en LI CENSE_NO m ust b e NULL; ot her wise bot h m ust be NOT NULL.

CHECK const r aint on STATE and LI CENSE.

A st u dent MAY hav e a colu mn v alue f or STATE. I f t h ey do, t h e STATE abbr eviat ion is v alid w it h r espect t o t he STATE_LOOKUP t able.

FOREI GN KEY con st raint on STATE.

3.3.1 Four Types of Errors •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

The r u les of r efer en t ial int egr it y ar e enfor ced d ur ing upd at es and delet es on par ent t ables By Kevin Owens and insert s and up dat es on ch ild t ab les. The SQL st at em ent s af fect ed b y r ef er ent ial in t eg r it y ar e: Pub lish er: Prent ice Hall PTR Pub Dat e: PARENTUPDATE I SBN:

Decem 0 5, 2 003 Youber cannot UPD ATE

st udent 0- 13 -0 850 33s-0w it h

a STATE in STATE_ LOOKUP w it h a valu e so as t o leav e a st at e abb rev iat ion t hat is n o long er in t h e STATE_LOOKUP

Pages: 44t8able.

PARENTDELETE

You cannot DELETE a STATE and leave st u dent s w it h a st at e t hat is no lon ger in t he par en t look up t able. For exam p le, if t h er e ar e st ud en t s w it h a Califor n ia license, w hich use t he ab br eviat ion 'CA,' y ou cannot delet e t he ' CA' r ow f rom Ef fect ively creat e an dLOOKUP. man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t STATE_ Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d LD - you wYou I NSERT a sttudent it h ust a st an at ed tcom h at plex is n otdat f ound in tfhe t CHI eaches hat cannot y ou n eed t o kn ow o buildw rob ab ases or y our b usiness. I NSERT STATE_ LOOKUP t able. For ex am ple, y ou cann ot inser t a st udent w it h a license and set inst t h e rSTATE n am t o aples, v alue notbook fou nd in t hes STATE_ LOOKUP t able. Using easy- t ofollow uct ionscolum an d ex t his pr esent t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CHI LD You cannot UPD ATE a st udent and r ep lace t he st at e w it h a st at e n ot f oun d in dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he UPDATE t he par en t st at e look up t able. bu sin ess evolv es. Topics cov er ed include: The f ollow in g SQL st at em ent s d em onst r at e t h e fou r err or t y pes an d t he Or acle er r or r et ur ned in g const s in ted. h e dat a dict ion tar w hen View t he const r aintr aint is violat Th ese in ser s,yupd at es, and delet es b eh ave assum ing t he dat a for t he STATE_ LOOKUP and STUD ENTS t ab les: Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re STATE_ LOOKU P

CA

Er r or han dling and except ions St a t e I nt er - pr ocess com mu nicat ions

St a t e D e scri pt i on

Califor n ia Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch NY New Yor k m or e NC Nor t h Car olin a Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

STU DENTS

[ Team St u deLiB nt ]I D

St u de nt N am e

Coll ege Ma j or

St a t us St a t e

Li ce nse N O

A10 1

John

Biology

Degr ee NULL

NULL

A10 2

Mar y

Mat h / Science

Degr ee NULL

NULL

A10 3

Kat hr y n

Hist ory

Degr ee CA

MV- 2 32- 1 3

A10 4

St even

Biology

Degr ee NY

MV- 2 32- 1 4

A10 5

William

En glish

Degr ee NC

MV- 2 32- 1 5

The f ir st t w o SQL st at em ent s ar e chang es t o t h e par ent t able. Pr ior t o chan ging t he p ar en t , Or acle m ust ex amine t he cont ent s of t he child t able t o ensur e dat a int egr it y.

PARENT-UPDATE •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR SQL> UPDATE state_lookup Dat e:state Decem ber 5, 2 003 2PubSET = 0'XX' I SBN: 013 -0 850 33 3 WHERE state =-0'CA'; Pages: 44 8

UPDATE state_lookup * ERROR at line 1: ORA-02292: integrity constraint Ef fect ively creat e an d man age com plex(SCOTT.FK_STUDENTS_STATE) dat abases w it h Or acle! Sy st ems and dat ab ase ex per t violated – child record found Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake PARENT-DELETE adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y SQL> DELETE FROM state_lookup 2 WHERE state = 'CA'; Com plex r ule enf orcem en t DELETE PL/ FROM SQL p state_lookup r ogr am un it s and langu age f eat u res * y pes and ERRORDat ata tline 1: comp osit e st r u ct u re ORA-02292: integrity constraint (SCOTT.FK_STUDENTS_STATE) Er r or – han dling and except ions violated child record found I nt er - pr ocess com mu nicat ions The n ex t t w o st at em en t s ar e chang es t o t h e ch ild t ab le. Each D ML on t h e child r equ ir es t hat Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Or acle ex am ine t h e cont ent s of t h e par ent t o ensur e dat a int egr it y . m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce CHILD-INSERT for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

SQL> INSERT INTO STUDENTS

2 VALUES [ Team LiB ] ('A000', 3 'Joseph','History','Degree','XX','MV-232-00'); INSERT INTO STUDENTS * ERROR at line 1: ORA-02291: integrity constraint (SCOTT.FK_STUDENTS_STATE) violated - parent key not found

CHILD-UPDATE



Table of Content s

Pr ogr am m ing Or astudents cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on SQL> UPDATE

2 SET state By Kevin Owens 3

= 'XX' WHERE student_id = 'A103';

UPDATE Pub lishstudents er: Prent ice Hall PTR * Pub Dat e: Decem ber 0 5, 2 003 ERROR I at line 1: SBN: 0- 13 -0 850 33 -0 ORA-02291: integrity constraint (SCOTT.FK_STUDENTS_STATE) Pages: 44 8 violated - parent key not found

For Or acle t o enf orce t h ese f our r ules, it m u st r ead f rom bot h t ables. A sim ple I NSERT int o a Ef fect ively creat e an age plex dat rabases w it h es Or tacle! Syacle st ems and dat ab ase ex per t STUDENTS t able, givdenman a for eigcom n k ey const ain t , r equir hat Or r ead t he Kevin Ow ens ex plor es PL/ Or acle's answ t o t h e St r uct ur ed Query Langu agem( ust SQL) , an d STATE_ LOOKUP t able. I f wSQL, e D ELETE f r om t heerSTATE_LOOKUP t able, t h en Or acle r ead tt eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. he STUDENTS t ab le t o f ir st en su re t here is no st u dent r ow t hat con t ains a STATE v alue t h at r ef erences t he STATE_LOOKUP r ow . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant agofe tof aclet yfeat as ove, t rig gers and pr oced es- f eatORAu r es 02 t hat allow y our I n each heOr f our pes ur ofes ersuch r ors ab t he err or stnored um ber is t h eursame: 291 . dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ent essial evolv es. itTopics covical er edpar include: Refer int egr y is a crit t of a d at abase desig n. I t is r are f or a t able t o not be eit her a p arent or child of som e ot her t able. I f you ev er look at a dat a mod el pr int ed on a lar ge scale gr aphics plot t er , t h e fir st t h in g you w ill not ice ar e t ables w it h no lin es—no par ent s View in g en const and no childr . r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t

3.3.2PL/Delete SQL p r ogr Cascade am un it s and

langu age f eat u res

Dateat he t y pes st r u ct u kreey sy nt ax t o specif y a d elet e cascad e feat ur e. Th is You hav opt and ion wcomp it h inosit t hee f oreign feat u re only aff ect s delet e st at em en t s in t he p arent t able. Er r or han dling and except ions Wit h t his op t ion, a delet e fr om t he par en t w ill au t omat ically delet e all r elev ant ch ild ren. Had I nt er - pr ocess com mu nicat ions w e cr eat ed t he f or eign k ey const rain t in Scrip t 3 - 1, " Foreign Key, " w it h t he DELETE CASCADE opt ionDeclar , t henatt he ollowin g SQL w ou ld d elet e ar t hye krecor in t hef or STATE_LOOKUP le for iv e fconst r aint s, including p rim ey , udnique, eign k ey, ch eckt ab , and m uch Califormnor iaeplus all st udent s t hat hav e a Calif orn ia license. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. SQL> [ TeamDELETE LiB ] FROM state_lookup 2 WHERE state = 'CA';

The D ELETE CASCADE syn t ax is:

[ Team LiB ]

ON DELETE CASCADE

The sy nt ax f or t h e for eign con st raint , show n in Scrip t 3 - 1, can be r ew rit t en w it h t he cascad e opt ion as f ollow s:

ALTER TABLE students fk_students_state • ADD CONSTRAINT Table of Content s FOREIGN state_lookup Pr ogr am m ing KEY Or a cl e(state) ® Tr i gger s REFERENCES and Stor e d P roce dure s, Thir d Edi ti(state) on ON DELETE CASCADE; By Kevin Owens ThePub d elet e cascad e opt ion should be t he except ion r at her t han t h e r ule. Lot s of d at a can be lish er: Prent ice Hall PTR inadv er t en t ly lost w it h an accident al d elet e of a row in t he par ent looku p t able. There are Pub Dat e: Decem ber 0 5, 2 003 app licat ions wh er e t h is opt ion is v er y u sefu l. I f dat a is t em por ar y —only lives f or a sh ort t im e I SBN: 0- 13 -0 850 33 -0 and is ev en t ually delet ed—t hen t his is v er y conv enient . Pages: 44 8

Delet e cascade can span m ult iple t ables. A p arent can cascade t o a child and t hat child can cause a d elet e cascad e t o ot her t ables. I f t here is a f oreign k ey const r aint in t he chain, w it hout t h e cascade op t ion, t h e delet e fr om t h e par en t f ails. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Delet t hat er SQL, sev erOr al acle's t ablesansw can er p ott en fect ot her par tLangu s of t hage e sy(st em. , Aan d Kevines Ow enscascade ex plor esovPL/ o tthially e St af r uct ur ed Query SQL) lengt h y delet t haty ou sp ans t ab es rob m illions w ill rdat equir e com pary able ollback t eaches you we hat n eed t oles knan owd tdoelet build ust anofd row comsplex ab ases f or our brusiness. space t o wr it e u ndo infor m at ion. Rollb ack sp ace sh ould be analy zed if t h e cascade d elet e is excessiv e. Addit ionally , per for m ance r ent his t q ueries against t ables e aff ect ed. Using easyt o- follow inst r uct ions an d of exconcur am ples, book pr esent s tthe echniq ueswill to b t ake Con sider t he w hen ingt rig a dgers elet eand cascad e opt adv ant ag e of follow Or acleing feat ur esdeclar such as st ored prion. oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: Does t h e cascade f it t h e app licat ion? An accident al delet e f r om a p arent look t able should not delet e cu st omer account s. View in g const r aint s in t h e dat a dict ion ar y What is t h e ch ain b ein g d eclar ed ? Look at w hat t ab les cascad e t o ot her t ables. Consider tCom he pot entr ule ial im pact and plex enf orcem enm t agnit ud e of a d elet e and h ow it w ou ld im pact perf or man ce. PL/ SQL p r ogr am un it s and langu age f eat u res

3.3.3Dat Mandatory Foreign Key Columns a t y pes and comp osit e st r u ct u re The f or k eydling constand r ainexcept t s st ipulat Ereig r ornhan ionses t h e r ule t hat a child MAY be a m em ber of t he par en t . I f t he ch ild is a mem ber t h en t h er e m ust be int egr it y . A NOT NULL const rain t on t he for eig n k ey I nt er - pr ocess com mu nicat ions r ep laces MAY w it h MUST. Declar iv econst constr ain r aint s, Scrip including rimor arces y k tey nique, f or eign k ey, ch eck , and m uch The f or eig n at k ey t in t 3 - 1 penf h e, ur ule. m or e dentOracle MAY hav e a dr iver 's I f t hur eyesdo, t hirat is, aisman eminv b er of Pr ogr A amstmu ing Tr igger s and Stlicense. or ed Pr oced , Th d st Edat it eion aluable r esou rce STATE_ for dat abase LOOKUP. d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. This r ule can hav e a diff er ent flav or —rest at ed here: [ Team LiB ] A st u dent MUST hav e a d riv er' s licen se an d t he st at e is a m em ber of STATE_LOOKUP. The lat t er is st ill a st at em ent of r ef er ent ial in t eg r it y ; t her e st ill ex ist s a on e- t o- man y

r[ elat ion sh Team LiBip]. The ru le ch anges t o MUST w hen t he NOT NULL con st raint is declared on t he child colum n . The b usin ess r ules ar e r evised . Becau se t he STATE and LI CENSE ar e m andat ory , t h e CHECK const r aint is rem oved. The f oreign k ey relat ionship chang es f r om MAY t o MUST. Scrip t 3 - 2 D DL for t he STUDENTS and STATE_LOOKUP t ab les enf or ces t h e follow ing:

Ru le

Enf orced W it h

A st u dent is uniqu ely id en t if ied b y a STUDENT_ I D .

PRI MARY KEY con st rain t

A st u dent MUST hav e a d riv er' s licen se. Th e st at e and license com binat ion is un ique am ong all ot her st udent s.

UNI QUE const r ain t , NOT NULL on STATE, NOT NULL on LI CENSE

A st u dent MUST hav e a colum n v alu e for STATE. The of Content s STATE abbr Table eviat ion is v alid w it h r espect t o t he Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on STATE_ LOOKUP t able.

FOREI GN KEY con st raint , NOT NULL on STATE



By Kevin Owens

The D DL t o enf or ce t hese ru les is sim ilar t o Scrip t 3 - 1. Th er e is n o CHECK const r aint and NOT NULL con st rain t s ar e added. There is no chan ge t o t he STATE_LOOKUP t able t o accom m odat e lishch er:anges. Prent ice Hall PTR t he Pub ru le Pub Dat e: Decem ber 0 5, 2 003 0- 13 -0 850 33 -0 Scr iptI SBN: 3 -2 For ei gn Ke y w it h M an dat or y Con st r a in t s. Pages: 44 8

CREATE TABLE students (student_id VARCHAR2(10) NOT NULL, Ef fect ively creat e anVARCHAR2(30) d man age com NOT plex NULL, dat abases w it h Or acle! Sy st ems and dat ab ase ex per t student_name Kevin Ow ens ex plorVARCHAR2(15) es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d college_major NOT NULL, t eaches you w hat y VARCHAR2(20) ou n eed t o kn owNOT t o build rob ust an d com plex dat ab ases f or y our b usiness. status NULL, state VARCHAR2(2) NOT NULL, Using easy- t o- followVARCHAR2(30) inst r uct ions anNOT d exNULL) am ples, t his book pr esent s t echniq ues t o t ake license_no adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our TABLESPACE student_data; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv students es. Topics cov er ed include: ALTER TABLE ADD CONSTRAINT pk_students PRIMARY KEY (student_id) USING INDEX TABLESPACE student_index; View in g const r aint s in t h e dat a dict ion ar y ALTERCom TABLE plex students r ule enf orcem en t ADD CONSTRAINT uk_students_license UNIQUE (state, license_no) PL/ SQL p r ogr am un it s and langu age f eat u res USING INDEX TABLESPACE student_index; Dat a t y pes and comp osit e st r u ct u re ALTER TABLE students ADDEr CONSTRAINT r or han dling and fk_students_state except ions FOREIGN KEY (state) REFERENCES state_lookup (state); I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch

3.3.4m Referencing the Parent Syntax or e

Pr ogr am m ing Oracle iggerkseyand ed t ,Prt he oced ur es n, (Th d Ed it ion is an inv aluable r esou When y ou cr eat e a f orTreign conSt stor rain colum s) iron t hat for, eig n key r eference t h erce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly colum n( s) t h at m ak e up a PRI MARY KEY or UNI QUE con st r aint . I n t h e case w h er e a for eign int ellig en t , com plex dat abases. k ey refer ences a par ent pr imar y k ey, t he colum n does not need t o be specified. For ex amp le, Scrip t 3 - 2 u ses t he follow ing syn t ax : [ Team LiB ]

[ Team TABLE LiB ] students ALTER ADD CONSTRAINT fk_students_state FOREIGN KEY (state) REFERENCES state_lookup (state);

When no par en t colum n is r ef erenced, t h e defau lt r eferenced colu mn is t h e pr im ary k ey of t he par ent . Th e follow ing w ould w ork just as w ell.

ALTER TABLE students ADD CONSTRAINT fk_students_state FOREIGN KEY (state) REFERENCES state_lookup; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

When y our f oreign k ey refer ences a par ent colu mn w it h a u nique con st r aint , t hat par ent By Kevin Owens colum n m u st be specified in t h e ADD CONSTRAI NT st at em ent . Pub lish er: Prent ice Hall PTR

3.3.5 Referential across Schemas and Databases Pub Dat e: Decem ber 0 5, Integrity 2 003 I SBN: 0- 13 -0 850 33 -0

A f or eig n k ey Pages: 44 8in a t able can r ef er t o a par ent t able in anot her schem a. This is n ot desirab le, at least f r om a d at abase adm inist r at or 's p er spect ive. An app licat ion t hat sit s w holly w it hin a single schema is v er y p ort ab le. The ent ir e app licat ion t hat ex por t s as a single ow n er easily im por t s int o anot h er d at abase. When fu nct ionalit y spans schem as, t he m igr at ion is not su ch a sm oot h pr ocess. Of t en, t h e applicat ion is not fully p ort ed because t he f un ct ion alit y in t h e Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t ot her schem as is ov er looked in t he p ort . An ex por t d um p file w ill im por t w it h err or s. The Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d for eign k ey const r aint s will f ail because t he refer enced schema does not exist , t h e obj ect in t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. t he ref er enced schema does not exist , or pr iv ileges fr om t h e r ef er enced schem a hav e n ot been cr eat ed . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Refer ent ial int egr it y can be im plem en t ed , t o var ious d eg rees, across d at abases. Th is can b e dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he com plicat ed. Opt ions are t o u se t rigg er s, r efr esh ed m at erialized v iew s, or Or acle replicat ion. bu sin ess evolv es. Topics cov er ed include: Mat er ialized view s ar e a st r aigh t for w ar d an d b alanced solut ion. The m at erialized v iew becom es an ob ject in t he local schema. I t is r ef r eshed using dat a fr om an ot her dat ab ase. A dat abView ase lin is r eqruir eds along it ha tdict he CREATE in gk const aint in t h e w dat ion ar y ANY MATERI ALI ZED VI EW p r iv ileg e. The r ef r esh r at e of t he v iew does n ot m ak e t he d at a r eal- t ime but can b e near r eal- t im e if t h e m at erialized r eforcem r eshed Com plexv iew r uleisenf enfrt equent ly . Assu m e tSQL hat tphe st am ud enun t s'it sdat abase n eeds elat ively f resh dat a f r om a g over nm ent dr iver 's PL/ r ogr and langu age f reat u res license ag en cy . Th e st udent s' dat abase need s dat a fr om a LI CENSE t ab le. I n t his con t ex t t he license aga en t he comp dat abase heu re LI CENSE t able is a m ast er t able. Dat t ycy pesis and osit eand st r utct The LIErCENSE ist sexcept on t h eions gov ern m en t agency serv er , AGENCY.GOV, in a d at abase r or hant able dlingex and nam e PROD, w it h a u ser nam e/ passwor d of SCOTT/ TI GER. Th e LI CENSE t ab le m ust hav e a I nt er - pr. ocess pr im ary key The obcom jectmu ive nicat is t oions hav e a local sn apshot of t he LI CENSE t able t hat is r efr eshed once ev er y 15 m inu t es. Th is is not real- t im e bu t cert ain ly sat isf ies t h e needs of t he st u dent ' s ateivreem const aint s, p rim y kineyFigur , u nique, e 3- 3f.or eign k ey, ch eck , and m uch dat abDeclar ase. Th ot e rconn ectincluding iv it y is illust ratared m or e

Figu 3 -ed 3 .PrM at er i al, iz Vie w ., is an inv aluable r esou rce Pr ogr am m ing Oracle Tr igger s andr e St or oced ur es Thed ir d Ed it ion for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

The p r ocess st art s by cr eat in g a Mat er ialized View Log of t he LI CENSE t able on t he PROD. AGENCY. GOV dat ab ase. Th is log is u sed by Oracle t o t r ack ch anges t o t he m ast er t able. Th is dat a in log for m at is u sed t o ref resh t he m at erialized v iew in t he st ud en t 's •dat ab ase. Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

On t he rem ot e dat abase: By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

CREATEI SBN: MATERIALIZED 0- 13 -0 850 33 -0 VIEW LOG ON LICENSE; Pages: 44 8

On t he st u dent s' dat ab ase, cr eat e a link t o t h e rem ot e PROD d at abase; t h en cr eat e t he m at erialized v iew. This v iew w ill be r ef r eshed once ever y 15 m inut es. I f t he net w ork is dow n, t he st u dent ' s app licat ion st ill has access t o t he m ost r ecen t r efr esh . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CREATE DATABASE LINK prod.agency.gov dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he CONNECT TO scott IDENTIFIED BY tiger bu sin ess evolv es. Topics cov er ed include: USING 'prod.agency.gov'; CREATE MATERIALIZED View in g const r aint sVIEW in t h eSTUDENT_LICENSE_RECORDS dat a dict ion ar y REFRESH FAST NEXT SYSDATE + 1/96 AS SELECT FROM Com plex* r ule [email protected] orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res The st u dent s' t ables can n ow r efer en ce a local sn apshot of dat a fr om t h e gov er n ment t y peswand comp osit st rat u ct u re dat abDat aseat able it h license infeorm ion. except ions Cr eat Er ingr orm han at erdling ializedand v iew s r equ ir es non - defau lt pr iv ileges. The m at er ialized v iew shou ld b e creat ed w it h st or age clauses based on t h e size of t he snap sh ot . I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch

3.3.6m Multiple Parents and DDL Migration or e

Pr ogr amt able m ingf rOracle s and St or ed Prpoced ur esTh , Th ir d Ed ion up , is tan inv gr aluable r esou rce A child eq uentTr ly igger has mu lt iple looku t ables. e use of itlook ables eat ly en hances for abase ev elopers, prENTS oj ect leader s look in an d act m aint ain t r uly t he dat over all intdegr it y of t hed esign dat a. er Ths,e and STUD t ab le began wgit ht oabtuild w o- char er colum n int ellig en com abases. STATE. I nt ,t eg rit yplex wasdat added t o t hat colum n by cr eat ing a look up t able, STATE_ LOOKUP. On ce t he STATE_LOOKUP t able is populat ed, t he f or eign k ey con st rain t can be cr eat ed. The dom ain [ofTeam LiB ] eviat ion s and st at e descr ipt ion s can g row w it hout im pact t o ch ild t ab les. STATE abbr Look up t ab les ar e of t en ad ded t hr ough out t he dev elop ment pr ocess as a m eans t o imp rov e t he in t egr it y of t he d at a.

From en d [ TeamanLiB ] u ser 's perspect ive, m aint enan ce of look up t ab les u su ally addr esses t he su bject of end user roles an d p riv ileg es. For an y applicat ion t here are specific r oles and pr ivileges t o r un t he ap plicat ion . How ever , chang es t o t ab les such as STATE_ LOOKUP w ou ld, and shou ld , r eq uir e special access. Dev elopin g t he app licat ion soft w ar e t o su ppor t en d u ser m aint enan ce of look up t ab les is m ost ly cu t - and - past e. Most look up t ables hav e t w o colu mn s. Once t h e fir st look up m aint enance screen is developed, m aint en ance for ot her looku p t ables is som ew hat r ep et it iou s. App licat ion cod e t o disp lay looku p d at a f ollow s a st and ard pr act ice of never show ing t h e pr im ary key colum n. To display st ud en t d at a on a scr een r eq uires j oining t he STUDENTS and STATE_ LOOKUP t ables. For each st u dent , t he st udent nam e an d st at e descr ipt ion are sh ow n bu t n ot t h e t w o char act er st at e field. HTML f or m elem ent s such as dr op dow n list s are pop ulat ed w it h t he st at e descr ipt ion, but by u sin g t he st at e as t h e opt ion v alue. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

state_description Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

An obser v at ion of t he d at a out lin ed in t he t ab les on p . 10 8 m igh t lead one t o believ e t hat I SBN: 0- 13 -0 850 33 -0 st udent college maj or s should be in a look up t ab le as w ell. Th is addit ional looku p t ab le w ould Pages: 44 8 r est r ict t h e dom ain of college m ajor descr ipt ions t o t he values cont rolled t hr ough a look up t able. Th e MAJOR_ LOOKUP t able w ould st or e t he d escr ip t ions lik e " Biolog y" and " Mat h . " This add it ion w ould be mod eled w it h t h e ent it y diag ram sh ow n in Figur e 3- 4 . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Figu r e 3 - 4 . M ul t ip le Par e n t s. Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat t y pes comp osit e st r tuab ct uleret o a STUDENTS and STATE_ LOOKUP, illust r at ed in The ad ditaion of aand MAJOR_LOOKUP Figur e 3- 2 , is accom plish ed w it h t he f ollow in g. Assum e t her e is dat a pr esent in t he Er r or han dling and except ions STATE_ LOOKUP an d STUDENTS t able as out lined in on p. 108 . I nt er - pr ocess com mu nicat ions The look up t ab le, MAJOR_LOOKUP, m ust be cr eat ed and pop ulat ed. The follow in g in clu des t he CREATE scrip , pr im ary s,key , and datp arim load. Declar at iv e tconst r aint including ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. CREATE TABLE major_lookup VARCHAR2(2) NOT NULL, [ (major Team LiB ] major_desc VARCHAR2(15) NOT NULL) TABLESPACE student_data; INSERT INTO major_lookup values ('UD','Undeclared');

INSERT [ Team INSERT INSERT INSERT

INTO LiB ] INTO INTO INTO

major_lookup major_lookup major_lookup major_lookup

values values values values

('BI','Biology'); ('MS','Math/Science'); ('HI','History'); ('EN','English');

ALTER TABLE major_lookup ADD CONSTRAINT pk_major_lookup PRIMARY KEY (major) USING INDEX TABLESPACE student_index;

The STUDENTS t able m u st be chan ged. I t st or es t h e college m aj or as VARCHAR( 15) . This m ust b e r ep laced w it h a t w o- char act er f ield t h at w ill be a for eign k ey t o t he MAJOR_ LOOKUP t able. Th is appr oach cr eat es a t em por ar y cop y ( t able TEMP) of t he STUDENTS t able, includin g t h e dat a. The STUDENTS t able is dr opp ed ; a new STUDENTS t able is cr eat ed and t he sav ed d at a is m igr at ed back int o t he n ew STUDENTS t ab le. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE TABLE TEMP AS SELECT * FROM STUDENTS; Pub lish er: Prent ice Hall PTR

DROP STUDENTS; PubTABLE Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

CREATE TABLE students Pages: 44 8 (student_id VARCHAR2(10) NOT NULL, student_name VARCHAR2(30) NOT NULL, college_major VARCHAR2(2) NOT NULL, status VARCHAR2(15) NOT NULL, Ef fect ively creat e an d VARCHAR2(2), man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t state Kevin Ow ens ex plor esVARCHAR2(30)) PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d license_no tTABLESPACE eaches you wstudent_data; hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake INSERT INTO STUDENTS adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SELECT student_id, dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he student_name, bu sin ess evolv es. Topics cov er ed include: decode ( college_major, View in'Undeclared' g const r aint s in t h,e 'UD', dat a dict ion ar y 'Biology' , 'BI', 'Math/Science' , t'MS', Com plex r ule enf orcem en 'History' , 'HI', PL/ SQL 'English' p r ogr am un it s and , 'EN' langu age f eat u res ), Datstatus, a t y pes and comp osit e st r u ct u re state, Er r or han dling and except ions license_no FROM temp; I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch The n ew STUD ENTS t ab le is popu lat ed , bu t w it h BI f or Biolog y. The const r aint s ar e ad ded t o m or e t he STUDENTS t ab le. Th is inclu des: Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for1 .dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly PRI MARY KEY int ellig en t , com plex dat abases. 2 . UNI QUE const r ain t on STATE, LI CENSE No [ Team LiB ] 3 . CHECK const r aint on STATE and License No 4 . Foreign Key t o STATE_LOOKUP

5 . Foreign [ Team LiB ] Key t o MAJOR_ LOOKUP

1. ALTER TABLE students ADD CONSTRAINT pk_students PRIMARY KEY (student_id) USING INDEX TABLESPACE student_index; 2. ALTER TABLE students ADD CONSTRAINT uk_students_license UNIQUE (state, license_no) USING INDEX TABLESPACE student_index; 3. ALTER TABLE students • Table of Content s ADD CONSTRAINT ck_students_st_lic Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on CHECK ((state IS NULL AND license_no IS NULL) OR By Kevin Owens(state IS NOT NULL AND license_no is NOT NULL)); 4. ALTER TABLE students Pub er: Prent ice Hall PTR ADDlishCONSTRAINT fk_students_state Pub Dat e: Decem 0 5, 2 003 REFERENCES state_lookup; FOREIGN KEYber(state) I SBN: 0- 13 -0 850 33 -0

5. ALTER students Pages:TABLE 44 8 ADD CONSTRAINT fk_students_college_major FOREIGN KEY (college_major) REFERENCES major_lookup; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 3.3.7Ow Many-to-Many Relationships t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Dat a measyodelin t ools will r aw, at an the lev el, am an y-pr t omansy t rechniq elat ionship h t he Using t o-g follow inst d r uct ions d logical ex am ples, t his book esent ues t owt itake not at ion show in Figur e 35 . adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he Figucov r eer3ed - 5include: . M an y- t o- M a ny Rel at i onshi p. bu sin ess evolv es. Topics View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e The m od el in Figur e 3- 5 d em on st r at es t h at a st udent can t ak e sever al cour ses, w h ile each Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce cour se is t augh t t o m or e t han one st u dent . Th er e is a m any - t o- m any r elat ion sh ip b et w een for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly st udent s and cour ses. Phy sically , t his is not im plem en t ed d irect ly; r at her , w e include a crossint ellig en t , com plex dat abases. r ef erence t ab le. Th at cr oss- r efer en ce t able, STUD ENTS_COURSES, w ill cont ain all t he cou rses a st u dent plu s all st udent s t hat t ak e a par t icular cour se. The p hy sical m odel b ecom es [ Team LiBt akes, ] t he gr aph in Figur e 3- 6 .

Figu r e 3 - 6 . Ph y si cal M a ny - t o- M an y Re la t i on shi p.

[ Team LiB ]

The f ollow in g t yp es of const r aint s are com m only app lied w it h t he ph ysical im plement at ion of a m an y- t o- man y r elat ionship . We h ave a pr im ary key in STUD ENTS. We h ave a pr im ary key in COURSES. •

Table of Content s

We h ave CONCATENATED KEY in tdhEdi e crossr ef er ence Pr ogr am m ing Or aacl e ® Tr i gger s and StorPRI e d PMARY roce dure s, Thir ti on

t able,

STUDENTS_COURSES.

By Kevin Owens

Par t of t h is pr im ary k ey is a f or eig n k ey t o t he STUDENTS t able; par t of it is a for eig n k ey t o t h e COURSES t able.

Pub lish er: Prent ice Hall PTR

Pub Dathe:ave Decem ber eign 0 5, 2 003 We a for key

in STUDENTS_COURSES t hat ensur es each st ud en t in t hat t ab le 33 -0 isI SBN: also 0-a13st-0u850 dent in STUDENTS. The sam e colu mn in t he f or eig n k ey is par t of t he pr im ary Pages: 44 8key .

We h ave a for eign key in STUDENTS_COURSES t hat ensur es each cour se in t hat t able is also a cou rse in COURSES. The sam e colu m n in t his for eig n k ey is par t of t he p rim ar y k ey . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d When w e app ly t hese ru les in t he for m of const r aint s, w e w ill hav e t h ree CREATE TABLE t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. st at ement s, t hr ee PRI MARY KEYS, and t w o FOREI GN KEY const r aint s. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake The t able descr ipt ion f or t he COURSES t able is show n here: adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Name Null? Type -----------------------------------------------Com plex r ule enf orcem en t COURSE_NAME VARCHAR2(10) COURSE_DESC VARCHAR2(20) PL/ SQL p r ogr am un it s and langu age f eat u res NO_OF_CREDITS NUMBER(2,1); Dat a t y pes and comp osit e st r u ct u re The t able ipt ionand f or except t he STUDENTS_ COURSES t able is show n her e: Er r ordescr han dling ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Name Null? Type Pr ogr am m ing Oracle Tr igger s and St or-------ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce ----------------------------------------for dat abase d ev elopers, d esign er s, and pr oj ect VARCHAR2(10) leader s look in g t o b uild an d m aint ain t r uly STUDENT_ID int ellig en t , com plex dat abases. COURSE_NAME VARCHAR2(10) [ Team LiB ] The colum ns of t he cr oss- r efer en ce t able cont ain colu mn s t hat m ust r efer en ce t he p arent s, in t his case, STUD ENTS an d COURSES. Th is is fir st st ep. Ad dit ional colum ns can be added t o t his t able, su ch as t he pr of essor w ho t each es t he class an d wh en it is t aug ht . A cr oss-

r[ efTeam erence LiBt ab ] le can b e just t he j oining colum ns. I t can also cont ain addit ional at t r ibut es. The D DL for t his m any - t o- m any r elat ionship is sh ow in Scrip t 3 - 3.

Scr ipt 3 -3 M a n y- t o- M an y Re la t i onshi p. CREATE TABLE students (student_id VARCHAR2(10) NOT student_name VARCHAR2(30) NOT college_major VARCHAR2(15) NOT status VARCHAR2(20) NOT state VARCHAR2(2), license_no VARCHAR2(30)) TABLESPACE student_data; •

NULL, NULL, NULL, NULL,

Table of Content s

CREATE Pr ogr am mTABLE ing Or a clcourses e ® Tr i gger s and Stor e d P roce dure s, (course_name VARCHAR2(10) NOT NULL, By Kevin Owens course_desc VARCHAR2(20) NOT NULL, no_of_credits NUMBER(2,1) NOT NULL) TABLESPACE student_data; Pub lish er: Prent ice Hall PTR

Thir d Edi ti on

Pub Dat e: Decem ber 0 5, 2 003

CREATE TABLE students_courses I SBN: 0- 13 -0 850 33 -0 (student_id VARCHAR2(10) NOT NULL, Pages: 44 8 course_name VARCHAR2(10) NOT NULL) TABLESPACE student_data; ALTER TABLE students Ef fect ADDively CONSTRAINT creat e an dpk_students man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t PRIMARY (student_id) Kevin Ow ensKEY ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches USINGyou INDEX w hatTABLESPACE y ou n eed t o student_index; kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using t o- courses follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake ALTER easyTABLE adv ant ag e of Or acle pk_courses feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our ADD CONSTRAINT datPRIMARY ab ases t oKEY incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he (course_name) bu USING sin ess evolv es.TABLESPACE Topics cov erstudent_index; ed include: INDEX ALTER TABLE students_courses in g const r aint s in t h e dat a dict ion ar y ADDView CONSTRAINT pk_students_courses PRIMARY KEY (student_id, course_name) Com plex r ule enf orcem en t USING INDEX TABLESPACE student_index; PL/ SQL p r ogr am un it s and langu age f eat u res ALTER TABLE students_courses ADDDat CONSTRAINT a t y pes and fk_students_courses_st_id comp osit e st r u ct u re FOREIGN KEY (student_id) REFERENCES students (student_id); Er r or han dling and except ions ALTERI ntTABLE er - pr ocess students_courses com mu nicat ions ADD CONSTRAINT fk_students_courses_course Declar at iv e (course_name) const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch FOREIGN KEY m or e REFERENCES courses (course_name); Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly 3.3.8 Self-Referential Integrity int ellig en t , com plex dat abases. [Self Team LiB ] ial int egr it y is comm on in man y app licat ions. Self- r efer en t ial int egr it y allow s - r ef erent par ent - child r elat ionship s t o ex ist bet w een inst ances of t he sam e ent it y . For ex amp le, all pr of essors are in t h e follow ing PROFESSORS t ab le, in clud ing t he in divid ual depar t m ent heads.

[Som Team e prLiB ofessors ] hav e a d ep art m ent head. Th ese d ep art m ent heads ar e also p rof essor s. The follow ing creat es a t able and a pr imar y k ey, and t hen est ab lishes a self- r efer en t ial int egr it y const r ain t .

CREATE TABLE professors (prof_name VARCHAR2(10) NOT specialty VARCHAR2(20) NOT hire_date DATE NOT salary NUMBER(5) NOT dept_head VARCHAR2(10)) TABLESPACE student_data; •

NULL, NULL, NULL, NULL,

Table of Content s

ALTER TABLE professors Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d ADD CONSTRAINT pk_professors By Kevin Owens PRIMARY KEY (prof_name) USING INDEX TABLESPACE student_index;

Edi ti on

Pub lish er: Prent ice Hall PTR

ALTER TABLE professors Pub Dat e: Decem ber 0fk_professors_prof_name 5, 2 003 ADD CONSTRAINT I SBN: 013 -0 850 33 -0 FOREIGN KEY (dept_head) Pages: 44 8 professors (prof_name); REFERENCES

This p er m it s a scenar io w her e a p rof essor MAY hav e a depar t m en t head ( DEPT_HEAD) and if Figur e 3tEf hey ave acreat depar t mdent head, t h at plex colum n abases value MUST beacle! an ex NAME. fecthively e an man age com dat w it h Or Syiststing emsPROF_ and dat ab ase ex per t 7 sh ows, f or exam p le, t hatSQL, BlakOr e is Milt on' s depar Kevin Ow ens ex plor es PL/ acle's answ er t o ttm h eent St rhead. uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

Figu r e 3 - 7 . Se lf - Re fe r en t i al I nt egr i t y D at a. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t Self - Refer ent ial I ntam egr it y ,it fsorand t helangu af or em ioned PL/ SQL p r ogr un ageent f eat u resdat a, is one level d eep. The f oreign k ey defin it ion p er m it s un lim it ed nest in g. Mu lt ilev el nest in g is illust r at ed wit h t h e follow ing t y pes and stle r u TEMP ct u re w it h t hr ee colum ns: WORKER, SALARY, and exam Dat ple.aWe cr eat e acomp sam osit ple et ab MANAGER. A wor k er m ay or m ay not hav e a man ager. A m anag er mu st fir st b e inser t ed as a Er.r Wor or han except w or ker k erdling s canand be m anag ions er s of ot h er w ork ers wh o m ay m anag e ot her w or k er s. The r elat ion sh ip s am ong t hese w or ker s and t heir salaries is show n as w ell. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle CREATE TABLE TEMP Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esignPRIMARY er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly (worker VARCHAR2(10) KEY, int ellig en t , com plex dat abases. salary NUMBER(3), manager [ Team LiB ]

VARCHAR2(10) REFERENCES TEMP (worker));

Allen m anag es Bill an d Bet h . Bet h m an ages Cind y and Car l. Car l m anag es Dean an d D ave.

[ Team LiB ]

Allen (salary=10) manages: Bill (salary=10), Beth (salary=10) Beth (salary=10) manages: Cindy (salary=5), Carl (salary=5) Carl (salary=5) manages: Dean (salary=5), Dave (salary=5)

This d at a cont ain s m ult ilev el r elat ionsh ip s for m ing a log ical t ree or gan izat ion . A SELECT st at ement using a CONNECT BY an d START AT clau se enab les a qu er y t o r et u rn , for ex am ple, t he su m of all salaries st ar t ing at a specif ic point in t h e t r ee. Th e insert s for t h is dat a are:



Table of Content s

INSERT ('Allen', 10,s, Thir null Pr ogr am mINTO ing Or aTEMP cl e ® Trvalues i gger s and Stor e d P roce dure d Edi ti); on INSERT INTO TEMP values ('Bill' , 10, 'Allen'); By Kevin Owens INSERT INTO TEMP values ('Beth' , 10, 'Allen'); INSERT INTO TEMP values ('Cindy', 5, 'Beth' ); INSERT INTO TEMP values ('Carl' , 5, 'Beth' ); Pub lish er: Prent ice Hall PTR INSERT INTO TEMP values ('Dean' , 5, 'Carl' ); Pub Dat e: Decem ber 0 5, 2 003 INSERT INTO TEMP values ('Dave' , 5, 'Carl' ); I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

The f ollow in g is a START AT SELECT st at em ent t o r et ur n Bet h' s salar y includ in g all t hose w ho w or k for Bet h . This is t h e sum of salaries f or Bet h, Cin dy , and Car l, p lu s Dean and Dav e w ho ar e m anaged by Carl: t he sum is $30 .0 0. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake SQL> sum(salary) adv antSELECT ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our FROMt otemp dat2ab ases incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he START WITH worker='Beth' bu 3 sin ess evolv es. Topics cov er ed include: 4 CONNECT BY PRIOR worker=manager; View in g const r aint s in t h e dat a dict ion ar y SUM(SALARY) ----------Com plex 30 r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res

3.3.9Dat PL/SQL a t y pes and Error compHandling osit e st r u ct u with re Parent/Child Tables Er r koreyhan anderrexcept Foreign condling st r aint or s arions e capt u red w it h m ap ping an ex cep t ion t o t h e Or acle er r or, m inus 2 291 . The follow in g pr ocedu re in ser t s a st udent r ow and capt ur es t h e dup licat e I nt er - pr ocess com mu nicat ions insert s. I n t his case a dup licat e could be a pr im ary k ey const r ain t v iolat ion or a u nique const rDeclar ain t eratr or. h generat e t he DUP_VAL_ON_I except ion. k ey, ch eck , and m uch iv e Bot const r aint s, including p rim ar y k ey ,NDEX u nique, f or eign m or e The D DL in Scrip t 3 - 1 d eclar es a CHECK const r aint on STATE an d LI CENSE NO. Th e follow ing pr oced urm e ing insert s a stTr udigger en t sanand d capt ured es Pr d uplicat violat e t aluable he pr im ary key Pr ogr am Oracle St or oced ureesinsert , Th irsdt hat Ed it m ionay, is an inv r esou rce or u nique con st r aint , for eig n key const r aint , an d check const r aint . for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] CREATE OR REPLACE PROCEDURE insert_student(v_student_id VARCHAR2,

v_student_name VARCHAR2, [ Team LiB ] v_college_major VARCHAR2, v_status VARCHAR2, v_state VARCHAR2, v_license_no VARCHAR2) IS check_constraint_violation exception; pragma exception_init(check_constraint_violation, -2290); foreign_key_violation exception; pragma exception_init(foreign_key_violation, -2291); BEGIN INSERT INTO students VALUES (v_student_id, v_student_name, v_college_major, v_status, v_state, v_license_no); dbms_output.put_line('insert complete'); • Table of Content s EXCEPTION Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on WHEN DUP_VAL_ON_INDEX THEN By Kevin Owens dbms_output.put_line('PK or unique const violation'); WHEN check_constraint_violation THEN dbms_output.put_line('check constraint violation'); Pub lish er:foreign_key_violation Prent ice Hall PTR WHEN THEN Pub Dat e: Decem ber 0 5, 2 003 dbms_output.put_line('foreign key violation'); END; I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

3.3.10 The Deferrable Option Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t I n t his sect ion w e use t w o t ables t hat st ore generic p arent / ch ild d at a. The d at a m odel f or t h is Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d is show n in Figur e 3- 8 . t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

Figu r eions 3 -an 8 .d Pa r e ples, nt - Chi Re la t i on sshi p. ues t o t ake Using easy- t o- follow inst r uct ex am t hisldbook pr esent t echniq adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dlingdescr andipt except ions The PARENT t able ion is: I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Name Null? Type Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce ------------------------------ -------- -----------for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly PARENT_NAME VARCHAR2(2) int ellig en t , com plex dat abases. PARENT_DESC VARCHAR2(10) [ Team LiB ] The CHI LD t able descr ipt ion is:

[ Team LiB ] Name Null? ------------------------------ -------CHILD_NAME PARENT_NAME

Type -----------VARCHAR2(2) VARCHAR2(10)

The D DL, sh ow n n ex t , in clud es a DEFERRABLE op t ion on t h e for eign key const r aint .

CREATE TABLE parent CONSTRAINT pk_parent PRIMARY • (parent_name Table ofVARCHAR2(2) Content s KEY, VARCHAR2(10)); Pr ogr am mparent_desc ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE TABLE child (child_name VARCHAR2(10), parent_name VARCHAR2(2)); Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

ALTER TABLE child ADD CONSTRAINT fk_child_parent_name I SBN: 0- 13 -0 850 33 -0 FOREIGN KEY (parent_name) Pages: 44 8 parent (parent_name) DEFERRABLE; REFERENCES

This D EFERRABLE at t r ib ut e m eans t h at w e can choose t o d ef er t he const r aint and load a set of datively a int ocreat t he ep arent andage child t ables, witabases h out regar t o acle! refer ent ial int egr , un Ef fect an d man com plex dat w it hd Or Sy st ems andit ydat abder aset he ex per t assu pt ion w hen t h eSQL, load Or com plet es, t he Th en aLangu com mage it will KevinmOw enst hat ex plor es PL/ acle's answ er dt at oa t hw e ill Stbe r uctclean. ur ed Query ( SQL) , an d aut om at ically t he r ulet on ed dat a.ust Wean can loadplex 1 0 rdat ecord s int of ora ychild t eaches you w apply hat y ou n eed o knour ow load t o build rob d com ab ases our bt able usiness. t hat has no p arent s and t hen load t he par ent s. Validat ion occu rs on t he com mit . I f t h e dat a Using easy-violat t o- follow inst ions prion esent t echniq ues w e loaded es t he refr uct er ent ial an intdegexritam y rples, u le, tthhis e t book r ansact is sr olled b ack . t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our You can d ot ot hincor is in por SQL* Plus w it h t hr eules follow ing.ar e easy t o man age and m odif y as t he dat ab ases at e bu siness w hich bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf en t SET constraints ALLorcem DEFERRED; INSERT INTO child VALUES ('child_1','P1'); PL/ INTO SQL p child r ogr am VALUES un it s and langu age f eat u res INSERT ('child_2','P1'); INSERT INTO child VALUES ('child_3','P2'); DatINTO a t y pes and comp osit e('child_4','P3'); st r u ct u re INSERT child VALUES INSERT INTO child VALUES ('P1','a parent'); Er r or han dling and except ions INSERT INTO child VALUES ('P2','a parent'); INSERT INTO child VALUES ('P3','a parent'); I nt er - pr ocess com mu nicat ions COMMIT; Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e You can u se t his fu nct ionalit y in a st or ed p rocedur e w it h t he follow in g: Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] CREATE OR REPLACE PROCEDURE P IS BEGIN EXECUTE IMMEDIATE 'SET constraints ALL DEFERRED';

INSERT [ Team LiB ] INTO INSERT INTO INSERT INTO INSERT INTO INSERT INTO INSERT INTO INSERT INTO COMMIT; END P;

child child child child child child child

VALUES VALUES VALUES VALUES VALUES VALUES VALUES

('child_1','P1'); ('child_2','P1'); ('child_3','P2'); ('child_4','P4'); ('P1','a parent'); ('P2','a parent'); ('P3','a parent');

The g en er al mot iv at ion for t his is t hat t he dat a com es in an in con sist ent ord er . Th e afor em en t ioned p r ocedu re in ser t s all child r ows, t hen t he par ent s. Th e afor ement ion ed insert s con t ain h ar d- coded lit er al v alues. A m or e realist ic sit u at ion could inv olve recor ds r ead fr om a file u sin g t h e UTL_FI LE pack age. The inp ut file w ould cont ain man y r ow s out of ord er ; t hat is, all child record s follow ed by all par ent r ecor ds. I n t his case a p rocedur e could cont ain • Table of Content s a sim ple loop, it er at e ov er all child in ser t s f ollow ed by all p arent insert s, an d t hen perf or m Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on int egr it y checking u pon a com mit . I n v ery select sit u at ions t h is can b e a r eason able By Kevin Owens app roach. I n general, t here ar e ot her t ools av ailab le t o ob viat e t h e need f or t h is opt ion. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

You can w r it e an except ion hand ler ar ou nd each child in ser t an d shou ld t hat f ail, I SBN: 0- 13 -0 850 33 -0 because t her e is no par ent , y ou w rit e cod e in t h e except ion hand ler t o insert a par en t . Pages: 44 8 Follow ing t h e par ent in ser t , y ou inser t t he child. For ex am ple, a child inser t w ould b e enclosed w it hin an ex cept ion h andler block similar t o t he f ollowin g b lock , w hich m aps t he for eig n k ey const r ain t v iolat ion ( ORA- 02 291 ) t o an ex cep t ion. Upon an except ion, insert a p arent and t h en t h e ch ild . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. UsingDECLARE easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag eno_parent of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our EXCEPTION; dat ab ases PRAGMA t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he EXCEPTION_INIT (no_parent, -2291); bu sin ess evolv es. Topics cov er ed include: new_parent VARCHAR2 (2) := 'P6'; new_child VARCHAR2(10) := 'child_5'; BEGIN View in g const r aint s in t h e dat a dict ion ar y INSERT INTO child VALUES (new_child, new_parent); Com plex r ule enf orcem en t EXCEPTION WHEN no_parent THENlangu age f eat u res PL/ SQL p r ogr am un it s and INSERT INTO parent VALUES (new_parent, Dat a t y pes and 'no compdesc'); osit e st r u ct u re INSERT INTO child VALUES (new_child, Er r or han dling and new_parent); except ions END; I nt er - pr ocess com mu nicat ions Declar at iv r aint p rim ar ySQL k ey ,t ab u nique, orhen eignyou k ey,com ch eck mtuch You can steorconst e f ailed chs,ildincluding r ecor ds in a PL/ le and f w plet,eand in ser ing all m orent e s, y ou go b ack and load t he child record s saved in t he PL/ SQL t able. The PL/ SQL par t able w ou ld b e der iv ed fr om t he ch ild t ab le wit h t h e follow ing syn t ax: Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB temporary_table_type ] TYPE IS TABLE OF CHILD%ROWTYPE INDEX BY BINARY_INTEGER; temporary_table temporary_table_type;

[ Team LiB ] Anot h er opt ion is t o u se a t em por ary t able t o st ore f ailed child recor ds. This is a solu t ion similar t o using a PL/ SQL Table. The PL/ SQL t able is m an ip ulat ed lik e an ar ray . Th e t em por ary t able is accessed t h rou gh SQL. Wit h t his solut ion, y ou load ch ild r ecor ds in t o t his t em por ar y r eposit ory , load all par ent s, t h en load fr om t h e t em por ary t able int o t he fin al child t able. The SQL f or a t em por ar y t able is:

CREATE GLOBAL TEMPORARY TABLE CHILD_TEMP (child_name VARCHAR2(10), parent_name VARCHAR2(2))ON COMMIT DELETE ROWS; •

Table of Content s

The ef m err able ope ®t ion is aspow fuel dt ool b ut shs,ould bon e used as a st and ard pr act ice Pr ogrdam ing Or a cl Tr i gger and er Stor P roce dure Thir dnot Edi ti because it d isab les t h e v er y r ules t hat ar e st r ongly encour aged—ev en if t he defer red st at e is By Kevin Owens a t em por ar y one. The SQL* Plu s scr ipt and afor em en t ion ed st or ed p rocedur e set t he const r ain t t o a d ef err ed Pub lish er: Prent ice Hall PTR st at e w it h t he st at em en t : Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

SET CONSTRAINT ALL DEFERRED; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d This SETyou comwman is one f or tdefer r in grob t he aint .plex Th edat ot her opt ion t o r bepusiness. lace t eaches hat dy ou n eedopt t oion kn ow o build ustconst an d rcom ab ases f or isy our ALL w it h t he specific const r aint nam e—t hat wou ld b e FK_CHI LD_ PARENT_ NAME. Th is means yUsing our ap plicat ion codeinst specifically r efer enam cesples, a const t n ame. Thset echniq SET CONSTRAI NT ALL easyt ofollow r uct ions an d ex t hisrain book pr esent ues t o t ake only af fect cur rfeat en t ur t ran he gers cod eand is mstore g en ic b ur ecause it udoes not allow sp ecifically adv ant ag esofy our Or acle es sact suchion; as tt rig ored preroced es- f eat r es t hat y our rdat ef erence st rain As a m at t erw of st yle d p ref ence, ecifm ic odif ment iontin ab asesat ocon incor portatnam e bue.siness r ules hich ar ean easy t o er man agespand y as heg of const ain tevolv n ames. es in t he cod a r ecom m endat ion . bu sin ress Topics coveerisednot include: When w e creat e a const r ain t , using t h e follow ing DDL, it m eans t h at w e h ave t he opt ion t o w r it e View cod e,in or use SQL* o dat t emp or arily def g const r aint sPlus, in t ht e a dict ion ar y er t hat con st r aint . Un less w e DEFER t he const r ain t , ev er y t hing r emains t he sam e. But , if w e choose t o w rit e cod e t hat t emp orar ily Com r ule orcem t br eaks t heplex r ule, w eenf m ust fir stenDEFER t h e const r ain t . PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re r or hanchild dling and ions ALTEREr TABLE ADDexcept CONSTRAINT fk_child FOREIGN KEY (parent_name) I nt er - pr ocess com mu nicat ions REFERENCES parent (parent_name) DEFERRABLE; Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e An opt ion t o t his is t o in it ially cr eat e t he const r aint in a defer r ed st at e. The D DL for t his is t he follow ing . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] ALTER TABLE child ADD CONSTRAINT fk_child FOREIGN KEY (parent_name) REFERENCES parent (parent_name) DEFERRABLE

INITIALLY [ Team LiB ] DEFERRED; Wit h t his op t ion ev er y t hin g is r ever sed . When w e load dat a in t o t h e child an d t hen p arent t ables, t he con st r aint is defer r ed —t his is t h e same as not hav ing a const r aint . Sh ould we w ant t o w r it e code w it h t he con st r aint enfor ced, as w e p er f orm each insert , t hen we w ould pr ecede t hose insert st at ement s w it h :

SET CONSTRAINT ALL IMMEDIATE;

[ Team LiB ] •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

3.4 Check Declar ing a dat abase colum n t o st or e a person' s age st ar t s wit h t h e follow ing:

CREATE TABLE temp (age NUMBER);

•This com m and Table w ill of w Content ork , bs ut t he r ang e of t he d at a t y pe f ar sur passes t he d omain of a Pr ogr am's m ing Or The a cl e ®g Tr i gger Stor P roce dure d Edi ti on per son age. oal is tsoand rest r icte done's ag es,t oThir t he r ang e: 1 t o 1 25—an y valu e out side t h at rByange is rej ect ed. A dim en sion on t he d at at y pe can imp ose a r est r ict ion on t h e colu mn so t hat Kevin Owens any v alue, ou t sid e a t h ree- digit num b er , is inv alid dat a. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 temp (age NUMBER(3)); CREATE TABLE

A d imension scales dow n t he ran ge of v alid v alues. St ill, values f ar gr eat er t han 12 5 can be insert t hr p ossible. An age 9 99 is not ab le.dat I nabgener al,per a t Ef fect ed—any ively creat e eean ddigit mannum ageber comisplex dat abases w itof h Or acle! Sy staccept ems and ase ex CHECK const aint is es used t o r estOr r ict t he answ dat a er t o tao real w or ld ur dom To Langu rest r ictage v alu es t o, an d Kevin Ow ens rex plor PL/ SQL, acle's t h e St r uct ed ain. Query ( SQL) int eger vyou alues bet w eenn eed 1 and e a check on t he n .f or y our b usiness. t eaches w hat y ou t o 12 kn5, owcrt eat o build rob ustcon anst d rain comt plex datcolum ab ases Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: CREATE TABLE temp (age NUMBER(3)); in g const in t h e dat a dict ion ar y ALTERView TABLE tempr aint ADDs CONSTRAINT ck_temp_age CHECK ((AGE>0) AND (AGE 0) AND (AGE insert into temp values (130); insert into temp values (130) * ORA-02290: check constraint (SCOTT.CK_TEMP_AGE) violated.

When a r ow is in ser t ed or upd at ed an d t here is a check con st r aint , Or acle ev aluat es t he ch eck const r ain t as a Boolean ex pr ession. For t h e afor em en t ioned check, t he r ow is in ser t ed •pr ov ided t heTable exp ression of Content " tsh e AGE is w it hin t he ( 1 , 125) r ange" ev aluat es t o t r ue. The r ow is Pr ingit Or e ® TRUE. Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on r ejogr ectam edm if isa nclot By Kevin Owens

The CHECK con st rain t does n ot h ave t o be a cont inu ous r ang e. Su ppose w e w an t t o con st rain a colum n v alu e t o t he f ollow ing bou ndar ies. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

(NOT NULL) AND (range in 0-10 OR 999 OR 9999)

The chively eck const r aint t h age is w ould be t he in g. Ef fect creat e an df or man com plex datfollow abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CREATE TABLE temp dat ab ases t o incor por (a at e NUMBER); bu siness r ules w hich ar e easy t o man age and m odif y as t he ALTER TABLE temp ADD CONSTRAINT ck_temp_a CHECK bu sin ess evolv es. Topics cov er ed include: (((a>=0) AND (a 0) AND (width incor at e(height bu siness ALTER TABLE box ADD CONSTRAINT ck_box_length CHECK 2 ((length > 0) AND (length desc state_lookup Name Null? Type ------------------------------- -------- ----------• STATE Table of Content s NOT NULL VARCHAR2(2) PrSTATE_DESC ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dureNULL s, Thir d Edi ti on NOT VARCHAR2(30) By Kevin Owens

SQL> desc major_lookup Name ------------------------------Pub lish er: Prent ice Hall PTR MAJOR Pub Dat e: Decem ber 0 5, 2 003 MAJOR_DESC I SBN: 0- 13 -0 850 33 -0

Null? -------NOT NULL NOT NULL

Type ----------VARCHAR2(2) VARCHAR2(15)

Pages: 44 8

SQL> desc students Name Null? Type ------------------------------- -------- ----------STUDENT_ID NOT NULL VARCHAR2(10) EfSTUDENT_NAME fect ively creat e an d man age com plex NOT dat abases it h Or acle! Sy st ems and dat ab ase ex per t NULL w VARCHAR2(30) Kevin Ow ens ex plor es PL/ SQL, Or acle's NOT answNULL er t o tVARCHAR2(2) h e St r uct ur ed Query Langu age ( SQL) , an d COLLEGE_MAJOR t eaches rob ustVARCHAR2(15) an d com plex dat ab ases f or y our b usiness. STATUSyou w hat y ou n eed t o kn ow t o build NOT NULL STATE VARCHAR2(2) Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake LICENSE_NO VARCHAR2(30) adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he SQL> desct ostudent_vehicles bu sin ess evolv es. Topics cov er ed include: Name Null? Type ------------------------------- -------- ----------STATE NOT NULL VARCHAR2(2) View in g const r aint s in t h e dat a dict ion ar y TAG_NO NOT NULL VARCHAR2(10) VEHICLE_DESC NOT NULL VARCHAR2(20) Com plex r ule enf orcem en t STUDENT_ID NOT NULL VARCHAR2(10) PARKING_STICKER NOT NULL PL/ SQL p r ogr am un it s and langu age f eat u res VARCHAR2(10) SQL> Dat desc a t yparking_tickets pes and comp osit e st r u ct u re Name Null? Type Er r or han dling and except ions -------------------------------------- ----------TICKET_NO NOT NULL VARCHAR2(10) I nt er - pr ocess com mu nicat ions AMOUNT NOT NULL NUMBER(5,2) STATE NOT NULL VARCHAR2(2) Declar at iv e const r aint s, including pNOT rim ar y k eyVARCHAR2(10) , u nique, f or eign k ey, ch eck , and m uch TAG_NO NULL m or e SQL> desc professors Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Name Null? Type for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly ------------------------------- -------- ----------int ellig en t , com plex dat abases. PROF_NAME NOT NULL VARCHAR2(10) SPECIALTY NOT NULL VARCHAR2(20) [ Team LiB ] HIRE_DATE NOT NULL DATE SALARY NOT NULL NUMBER(7,2) TENURE NOT NULL VARCHAR2(3) DEPARTMENT NOT NULL VARCHAR2(10)

[ Team LiB ] SQL> desc courses Name ------------------------------COURSE_NAME COURSE_DESC NO_OF_CREDITS

Null? -------NOT NULL NOT NULL NOT NULL

Type ----------VARCHAR2(10) VARCHAR2(20) NUMBER(2,1)

SQL> desc students_courses Name ------------------------------STUDENT_ID COURSE_NAME PROF_NAME

Null? -------NOT NULL NOT NULL NOT NULL

Type ----------VARCHAR2(10) VARCHAR2(10) VARCHAR2(10)

•[ Team LiB ] Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

4.3 DDL The f ollow in g D DL is used t o creat e t he t ables f rom t he d at a m odel. The con st r aint nam es and t y pes ar e seen in t he dat a dict ionar y qu er ies of Ch apt er 5. Business r ules not enf or ced w it h con st r aint s are en for ced w it h t r ig gers and st ored pr oced ur es in Ch apt ers 6, 7, an d 8.



Table of Content s

DROP TABLE Pr ogr am m ing Orstudents_courses; a cl e ® Tr i gger s and Stor e d DROP TABLE professors; By Kevin Owens DROP TABLE courses; DROP TABLE parking_tickets; DROP TABLE student_vehicles; Pub lish er: Prent ice Hall PTR DROP TABLE students; Pub Dat e: Decem ber 0 5, 2 003 DROP TABLE state_lookup; I SBN: 0- 13 -0 850 33 -0 DROP TABLE major_lookup;

P roce dure s, Thir d Edi ti on

Pages: 44 8

-- SEQUENCE DROP SEQUENCE students_pk_seq; CREATE SEQUENCE students_pk_seq START WITH 201; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d -t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. -STATE_LOOKUP -Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake CREATE TABLE state_lookup adv ant ag e of Or acle feat ur es such t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our (state VARCHAR2(2) NOTasNULL, datstate_desc ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he VARCHAR2(30) NOT NULL) bu sin ess evolv es. Topics cov er ed include: TABLESPACE student_data; -View in g const r aint s in t h e dat a dict ion ar y -- MAJOR_LOOKUP -Com plex r ule enf orcem en t CREATE TABLE major_lookup (major VARCHAR2(2) NULL, PL/ SQL p r ogr am un it s andNOT langu age f eat u res major_desc VARCHAR2(15) NOT NULL) TABLESPACE student_data; Dat a t y pes and comp osit e st r u ct u re -- Er r or han dling and except ions -- STUDENTS -- I nt er - pr ocess com mu nicat ions CREATE TABLE students Declar at iv e constVARCHAR2(10) r aint s, includingNOT p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch (student_id NULL, m or e student_name VARCHAR2(30) NOT NULL, college_major VARCHAR2(2) NOT NULL, Pr ogr am m ing Oracle Tr igger s and St orNOT ed PrNULL, oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce status VARCHAR2(15) forstate dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly VARCHAR2(2), int license_no ellig en t , com plex dat abases. VARCHAR2(30)) TABLESPACE student_data; [ Team LiB ] --- STUDENT_VEHICLES --

CREATE TABLE student_vehicles [ Team LiB ] (state VARCHAR2(2) tag_no VARCHAR2(10) vehicle_desc VARCHAR2(20) student_id VARCHAR2(10) parking_sticker VARCHAR2(10) TABLESPACE student_data; --- PARKING_TICKETS -CREATE TABLE parking_tickets (ticket_no VARCHAR2(10) amount NUMBER(5,2) state VARCHAR2(2) tag_no VARCHAR2(10) • Table of Content s TABLESPACE student_data;

NOT NOT NOT NOT NOT

NULL, NULL, NULL, NULL, NULL)

NOT NOT NOT NOT

NULL, NULL, NULL, NULL)

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By --Kevin Owens -- COURSES -Pub lishTABLE er: Prent ice Hall PTR CREATE courses Pub Dat e: Decem ber 0 5, 2 003 (course_name VARCHAR2(10) NOT NULL, course_desc I SBN: 0- 13 -0 850VARCHAR2(20) 33 -0 NOT NULL, no_of_credits NUMBER(2,1) NOT NULL) Pages: 44 8 TABLESPACE student_data;

--PROFESSORS Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t -Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d CREATE TABLE professors t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. (prof_name VARCHAR2(10) NOT NULL, specialty Using easy- t o- followVARCHAR2(20) inst r uct ions anNOT d exNULL, am ples, t his book pr esent s t echniq ues t o t ake NOTt rig NULL, advhire_date ant ag e of Or acleDATE feat ur es such as gers and st ored pr oced ur es- f eat u r es t hat allow y our NUMBER(7,2) datsalary ab ases t o incor por at e bu siness rNOT ules NULL, w hich ar e easy t o man age and m odif y as t he VARCHAR2(3) NOT NULL, bu tenure sin ess evolv es. Topics cov er ed include: department VARCHAR2(10) NOT NULL) TABLESPACE student_data; View in g const r aint s in t h e dat a dict ion ar y -Com plex r ule enf orcem en t -- STUDENTS_COURSES -PL/ TABLE SQL p r ogr am un it s and langu age f eat u res CREATE students_courses (student_id VARCHAR2(10) NOT NULL, Dat a t y pes andVARCHAR2(10) comp osit e st r uNOT ct u reNULL, course_name prof_name VARCHAR2(10) NOT NULL) Er r or han dling and except ions TABLESPACE student_data; I nt er - pr ocess com mu nicat ions ----------------------------------------- PRIMARY CONSTRAINTS Declar atKEY iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch ---------------------------------------m or e ALTER TABLE state_lookup ADDamCONSTRAINT (state) Pr ogr m ing Oracle pk_state_lookup Tr igger s and St or edPRIMARY Pr oced urKEY es , Th ir d Ed it ion , is an inv aluable r esou rce INDEX TABLESPACE student_index; forUSING dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. ALTER TABLE major_lookup [ Team ADD CONSTRAINT LiB ] pk_major_lookup PRIMARY KEY (major) USING INDEX TABLESPACE student_index; ALTER TABLE students

ADD LiB CONSTRAINT pk_students PRIMARY KEY (student_id) [ Team ] USING INDEX TABLESPACE student_index; ALTER TABLE student_vehicles ADD CONSTRAINT pk_student_vehicles PRIMARY KEY (state, tag_no) USING INDEX TABLESPACE student_index; ALTER TABLE parking_tickets ADD CONSTRAINT pk_parking_tickets PRIMARY KEY (ticket_no) USING INDEX TABLESPACE student_index; ALTER TABLE courses ADD CONSTRAINT pk_courses PRIMARY KEY (course_name) • Table of Content s USING INDEX TABLESPACE student_index;

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens ALTER TABLE professors ADD CONSTRAINT pk_professors PRIMARY KEY (prof_name) Pub lish er: Prent iceTABLESPACE Hall PTR USING INDEX student_index; Pub Dat e: Decem ber 0 5, 2 003

ALTER I TABLE SBN: 0- 13students_courses -0 850 33 -0 ADDPages: CONSTRAINT pk_students_courses 44 8 PRIMARY KEY (student_id, course_name) USING INDEX TABLESPACE student_index; ----------------------------------------UNIQUE and eCHECK CONSTRAINTS Ef fect ively creat an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t ---------------------------------------Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER students t eachesTABLE you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ADD CONSTRAINT uk_students_license UNIQUE license_no) Using easy- t(state, o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake USING TABLESPACE student_index; adv ant ag e INDEX of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he ALTER TABLE bu sin ess evolv students es. Topics cov er ed include: ADD CONSTRAINT ck_students_st_lic CHECK ((state IS NULL AND license_no IS NULL) OR View in g(state const r aint in t hNULL e dat AND a dictlicense_no ion ar y IS sNOT is NOT NULL)); plex students r ule enf orcem en t ALTERCom TABLE ADD CONSTRAINT ck_students_status PL/ SQL(status p r ogr am IN un it('Degree','Certificate')); s and langu age f eat u res CHECK a t y pes and comp osit e st r u ct u re ALTERDat TABLE professors ADD CONSTRAINT ck_professors_department Er r or han dling and except ions CHECK (department IN ('MATH','HIST','ENGL','SCIE')); I nt er - pr ocess com mu nicat ions ALTER TABLE professors ADD CONSTRAINT Declar at iv e const rck_professors_tenure aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch CHECK m or e (tenure IN ('YES','NO')); ALTER professors Pr ogr amTABLE m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce ADD CONSTRAINT ck_professors_salary for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly CHECK (salary < abases. 30000); int ellig en t , com plex dat ---------------------------------------[ Team -FOREIGN LiB ] KEY CONSTRAINTS ----------------------------------------- students references state_lookup --

ALTER [ Team TABLE LiB ] students ADD CONSTRAINT fk_students_state FOREIGN KEY (state) REFERENCES state_lookup; --- students references major_lookup -ALTER TABLE students ADD CONSTRAINT fk_students_college_major FOREIGN KEY (college_major) REFERENCES major_lookup; --- student_vehicles references state_lookup -ALTER TABLE student_vehicles ADD CONSTRAINT fk_student_vehicles_state FOREIGN KEY (state) REFERENCES state_lookup; -• Table of Content s -- student_vehicles references students Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on -By Kevin Owens ALTER TABLE student_vehicles ADD CONSTRAINT fk_student_vehicles_stud FOREIGN KEY (student_id) REFERENCES students; -- Pub lish er: Prent ice Hall PTR Dat e: Decem ber 0 5, 2references 003 -- Pub parking_tickets students_vehicles -I SBN: 0- 13 -0 850 33 -0 ALTERPages: TABLE 44 8 parking_tickets ADD CONSTRAINT fk_parking_tickets_state_tag FOREIGN KEY (state, tag_no) REFERENCES student_vehicles; --students_courses references students Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t -Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER students_courses t eachesTABLE you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ADD CONSTRAINT fk_students_courses_st_id FOREIGN (student_id) Using easy- tKEY o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake REFERENCES adv ant ag e of Orstudents acle feat ur (student_id); es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our -dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he -students_courses courses bu sin ess evolv es. Topicsreferences cov er ed include: -ALTER TABLE students_courses in g const r aint s in t h e dat a dict ion ar y ADDView CONSTRAINT fk_students_courses_course FOREIGN KEY (course_name) Com plex r ule enf orcem en t REFERENCES courses (course_name); -PL/ SQL p r ogr am unreferences it s and languprofessors age f eat u res -- students_courses -a t y pes and comp osit e st r u ct u re ALTERDat TABLE students_courses ADD CONSTRAINT fk_students_courses_prof Er r or han dling and except ions FOREIGN KEY (prof_name) REFERENCES professors (prof_name); I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch [ Team LiB m or e ] Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

4.4 Sample Data

STATE_ LOOKU P St a t e

St a t e D e scri pt i on

CA

Califor n ia

• NY

New Yor k

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

NC

Nor t h Car olin a

By Kevin Owens

Pub lish er: Prent ice Hall PTR

M AJOR_ LOOKU P

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ma j or

Ma j or D e scr ipt ion

UD

Undeclar ed

BI Biology Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t MS Mat h / Science Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t HI eaches you w hat y ou n eed t o kn ow t o build Hist rob ust ory an d com plex dat ab ases f or y our b usiness. EN easy- t o- follow inst r uct ions an d ex am ples, En glish Using t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

STU DENTS View in g const r aint s in t h e dat a dict ion ar y St u de nt I D St u de nt N am e Coll ege Ma j or Com plex r ule enf orcem en t A10 1 John Biology PL/ SQL p r ogr am un it s and langu age f eat u res A10 2 Mar y Mat h / Science

St a t us St a t e

Li ce nse N o

Degr ee NULL

NULL

Degr ee NULL

NULL

A10 3Dat a t y pes and Katcomp hr y n osit e st r u ct u re

Hist ory

Degr ee CA

MV- 3 2- 13

and except ions A10 4Er r or han dling St even

Biology

Degr ee NY

MV- 2 32- 1 4

A10 5I nt er - pr ocessWilliam com mu nicat ions

En glish

Degr ee NC

MV- 2 32- 1 5

Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e

STU DENT_ VEHI CLES

Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Stellig a t e en t , com Ta g plex N o dat abases. V e hicle De sc St u de nt I D Par k ing St i ck er int CD ]23 48 [ CA Team LiB

19 97 Must ang

A10 3

C- 1 01- AB- 1

NY

MH 870 9

19 98 GTI

A10 4

C- 1 01- AB- 2

NY

JR 983 7

19 82 Civ ic

A10 4

C- 1 01- AB- 3

[ Team LiB ]

PARKI NG_ TI CKETS Tick e t N o

Am oun t

St a t e

Ta g N o

P_0 1

5. 00

CA

CD 23 48

P_0 2

5. 00

NY

MH 870 9

P_0 3

5. 00

NY

MH 870 9

P_0 4

5. 00

NY

JR 983 7



Table of Content s

PROFESSORS

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Prof N a m e

Blake

Sp ecia lt y

H ir e D at e

Sa la ry Te nur e D e par t m en t

Mat h em at ics 07 - Jul- 03

10 00

YES

MATH

07 - Jul- 02

10 00

YES

HI ST

En glish

08 - Jul- 01

10 00

YES

ENGL

Jones

Eu ro Hist

05 - Aug- 0 0

10 00

YES

HI ST

Cr um p

Ancient Hist

04 - Aug- 9 9

10 00

YES

HI ST

Pub lish er: Prent ice Hall PTR

MiltPub on Dat e:

Am Decem ber 0 5, 2 003

WilsonI SBN: 0- 13 -0 850 33 -0

Hist or y

Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

COURSES

Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of OrN acle rig gers and st ored pr oced ur es- fN eat r esCrt edi hat tallow y our Course a m feat e ur es such as tCourse D e sc o uof s dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he ENGL101 En glish Lit 3 bu sin ess evolv es. Topics cov er ed include: MATH10 1

Algebr a

3

View in g const r aint s in t h eAm datHist a dict HI ST102 or yion ar y

3

Com t BI OL1 03 plex r ule enf orcem enBiology

3

PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re

STU DENTS_ COU RSES

Er r or han dling and except ions St u de nt I D Course N a m e Prof N a m e I nt er - pr ocess com mu nicat ions A10 1 ENGL101 Wilson Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch A10 1m or e MATH10 1 Blake A10 2 HI ST102 Cr um p Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for and pr oj ect leader s look in g t oMilt b uild A10dat 3 abase d ev elopers, d esign erHIs,ST102 on an d m aint ain t r uly int ellig en t , com plex dat abases. A10 4 BI OL1 03 Blake [ Team LiB ] A10 4 ENGL101 Wilson [ Team LiB ]

[ Team LiB ]

Chapter Five. Viewing Constraints in the Data Dictionary 5. 1 WHAT YOU CAN SEE 5. 2 DI CTI ONARY VI EWS: AN OVERVI EW 5. 3 CONSTRAI NT VI EWS •

5. 4 USER_CONS_COLUMNS Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

5. 5 USER_CONSTRAI NTS

By Kevin Owens

5. 6 DATA DI CTI ONARY CONSTRAI NT SCRI PTS Pub lish er:5.Prent Hall 6. 1ice Con st rPTR aint s

on a Table

Pub Dat e: Decem ber 0 5, 2 003

Ch asing I SBN:5.0-6. 132-0 850 33 -0

a Const r aint Name

Pages: 44 8

5. 6. 3 CHECK Const rain t Ru le 5. 6. 4 Qu er y ing Parent Tables

Ef fect ively 5. creat 6. 5 e Quan erdy ing manChild age com Tables plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 5. 6. 6 Con st r n aint usow t o build rob ust an d com plex dat ab ases f or y our b usiness. t eaches you w hat y ou eedStt oatkn 6. 7follow Validat edr uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Using easy-5.t oinst adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our This v espor t wo oses. rFirst w hich e look constt or aint for m at ion in tyh easdat a dat abchap asest er t o ser incor at epu burpsiness ules, w ar eateasy maninage and m odif t he dict ionar y , specif ically t he dat a dict ion ary view s USER_CONSTRAI NTS and bu sin ess evolv es. Topics cov er ed include: USER_CONS_COLUMNS. An und er st and ing of t hese view s can b e a b asis f or a br oad un derst an ding of how con st r aint s are en for ced by Oracle. View in g const r aint s in t h e dat a dict ion ar y Secon d, t h is is a st ar t ing point f or ex plor ing t he dat a dict ion ary . You w ill be able t o ex t r act a w ide vCom ar iet y of r in forenf m at ion f ren om plex ule orcem t t he d at a d ict ion ary : con st r aint inf orm at ion, t r ig ger s, st or ed pr oced ur es, sequ en ce d ef init ions. An yt h in g you def in e in t he dat abase you can r ev ersePL/ SQL r ogr am un it s and langu age f eat u res engineer w it hp SQL. Datple a t yscr pes osit e er st r con u ct ut ain re sam ple out put assu min g t h ey w er e r un against t he The sam ip and t s in comp t his chapt DDL f or t he mod el in Ch apt er 4. Er r or han dling and except ions I ntLiB er - pr [ Team ] ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

5.1 What You Can See Ob ject s t hat w e creat e can alw ays b e ext r act ed f r om v iew s t h at b eg in w it h " USER_. " I f we creat e 1 0 t ables in ou r sch em a, t hen a quer y of USER_ TABLES will r et ur n 10 r ow s—each row r et ur ning at t r ibut e infor m at ion about a t ab le. Sup pose t hat an Or acle account user nam ed SMI TH creat es a t able called PAYROLL and gr ant s all pr ivileges on PAYROLL t o t h e user SCOTT. Can SCOTT see PAYROLL in USER_TABLES? No, but SCOTT can see PAYROLL fr om ALL_TABLES. The ALL_ TABLES view show s not j ust t ab les w e cr eat e but also ot h er t ables t o w hich w e hav e been g r ant ed access. The v iew s w e ar eofcon cer ned • Table Content s w it h ar e n amed w it h t he f ollow ing pr efix es: Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

USER ALL

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 DBA I SBN: 0- 13 -0 850 33 -0

These Pages: pr efix44 es8 are an aid in lim it ing t he scope of w h at w e w ant t o see, need t o see, or sh ould be allow ed t o see. To see all t ables w e creat e in our schem a, w e qu er y USER_ TABLES; t o see all t ab les w e cr eat e plus t ables t o w hich w e hav e r eceived pr ivileges fr om ot her users, w e qu er y ALL_TABLES. A user w it h t h e DBA r ole or SELECT_CATALOG_ROLE can q uer y DBA_TABLES t o select a list of all t ables in t he d at abase. The scope d ef ined b y each pr efix is Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t t he follow in g: Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. USER_ View wit h t hinst is pr ef ix r etan urd n aexram esult sett his descr ibing h ose sob ject s creat in y our Using easyt o-sfollow r uct ions ples, book pr tesent t echniq ues ted o t ake To feat see ur a es listsuch of allast hteriguser t his pr groced ou p:ur es- f eat u r es t hat allow y our adv ant agsch e ofem Ora.acle gersview ands stinored dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he [ View full w idth] bu sin ess evolv es. Topics cov er ed include: SELECT view_name FROM all_views WHERE view_name like 'USER%'; View in g const r aint s in t h e dat a dict ion ar y plexs r wit ulehenf ALL_ComView t h orcem is pr ef en ix tr et u r n ob ject s creat ed in y our schem a p lu s t hose ob ject s t hat hav e been cr eat ed in ot her account s and t o wh ich y ou hav e been g ran t ed PL/ SQL p r ogr am un it s and langu age f eat u res pr iv ileges. The ALL view s fr equent ly in clu de a colum n f or OWNER—t o r eflect t h e t h ecomp object Dat aowt yner pesofand ositt oe w sthich r u ct uyou re hav e access. You w on' t see OWNER as a colu m n in USER_TABLES becau se y ou ar e t he ow n er of all t able nam es in t his v iew ; how ever , OWNER is aand coluexcept m n in ions ALL_TABLES. Er r or han dling DBA_ View s wit h t h is pr ef ix pr ov ide inf orm at ion abou t t h e en t ir e dat abase. A quer y of I nt er - pr ocess com mu nicat ions OWNER an d TABLE_NAME f r om DBA_TABLES r et ur ns t he t ab le own er and nam e of all at t ab in t he dats,abase—including base t ablesf or oweign ned kby Declar iv les e const r aint including p rim artyh ke ey , u nique, ey,SYS. ch eck , and m uch m or e Not ev ery v iew has a USER, ALL, an d DBA p refix . Th er e ar e som e view s t hat only ex ist in t he DBA OneTrexigger am ple is t h BA_ DATA_FI LES. used in Ch rapt er rce 3 Pr ogrview am m scope. ing Oracle s and Steorview ed PrDoced ur es , Th ir d EdThis it ionv, iew is anis inv aluable esou t o illust r at e ind exelopers, sp ace usage a pr im arect y key ind ex . I n in gener a van iewd in USER for dat abase d ev d esignf rom er s, and pr oj leader s look g t o al, b uild m aint ainscope t r uly hasellig a count er par t in dat t h eabases. ALL and DBA scop e. int en t , com plex Access o t he [ Team tLiB ] DBA v iew is som et imes g iv en in a developm ent en vir onm ent . Th er e is n o h arm allow in g developers t o ex plor e t he Oracle dict ionar y ; h owev er , y ou can ach iev e t his access w it hout r eleasing t he D BA r ole. By default , w it h t h e t y pical CONNECT an d RESOURCE r oles—usually t h e defau lt giv en t o an app licat ions d ev eloper—on e cannot access t hese t ables.

You can LiB g ran [ Team ] t t h e SELECT ANY TABLE pr iv ilege or SELECT_CATALOG r ole t o a user and t his w ill allow one t o access t he full dat a dict ion ary . Th e m ore one un derst an ds t h e dat a dict ionar y , t he m or e in t ouch t hey ar e w it h t he com plex oper at ion s of t he dat abase an d t h e m or e t hey ar e sen sit iv e t o su ch t h in gs as SQL st at em ent t uning .

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

5.2 Dictionary Views: An Overview Ther e ar e some im plicit r elat ionships am ong t h e dat a dict ionar y view s. Fin ding t hese r elat ion sh ip s is oft en a result of ex per im ent ing w it h SQL qu er ies against t he dat a dict ionar y . Fort unat ely , t her e is a g ood d eal of con st ancy w it h n am es u sed in t he d at a dict ionar y . For exam ple, t h e view USER_TABLES cont ains a sin gle r ow f or each t ab le. Each r ow cont ain s det ailed inf or mat ion ab out a t able such as t h e phy sical st orag e par am et er s of t hat t ab le. Th is dat a pr ov ides ex t ent infor m at ion t elling y ou how t h e t able w ill g row phy sically . The USER_TAB_COLUMNS v iew cont ains on e r ow for each colu m n of each t able in I f ofa Content t able has 1 0 colum n s, t hen you w ill fin d 1 0 r ow s in •USER_TABLES. Table s USER_TAB_ dets ailin g infe or at ion out dt he atont r ibu t es of each colu mn , such as t he Pr ogr am m ing COLUMNS, Or a cl e ® Tr i gger and Stor d Pm roce dureab s, Thir Edi ti colum n d at a t yp e. Th e colum n n am e TABLE_ NAME is com m on bet w een USER_TABLES an d By Kevin Owens USER_TAB_ COLUMNS so it is easy t o join t hese view s. ThePub in for m at ion y ou obt ain fr om dat a d ict ion ary view s is useful t hr oug hout all ph ases of a lish er: Prent ice Hall PTR pr oj ect . You can' t p ossibly m aint ain fam iliar it y w it h all d at a d ict ion ary v iew s; t his is w h er e Pub Dat e: Decem ber 0 5, 2 003 t he SQL* Plu s DESCRI BE b ecom es m ost v alu able. We m ay not be su re wh at colum ns are in a -0 850 33 -0 v iew , wI SBN: h ich 0-m13akes it diff icu lt t o w rit e a m ean ingf ul q uery , b ut w e can f irst descr ibe t h e view . 44 8 t he colum n nam es. This wPages: ill show I f you r accou nt has t h e DBA r ole, t hen y ou can st art discover ing by f irst list ing all v iew nam es w it h t he q uery : Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake SELECT ORDER adv ant agview_name e of Or acle FROM feat ur dba_views es such as t rig gers BY and1; st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: The D BA v iew s q uery w ill ret ur n t he full set of d at a d ict ion ary v iew s inclu ding t h e USER, ALL, and DBA view s, as w ell as t he v$ per for m ance v iew s ( Ch apt er 2, Sect ion 2. 1 2, illust r at es a View in gy const t h eance dat av iew dict)ion sam ple quer usingr aint t h e sv$ininst . I fary you don' t h ave t he DBA role, y ou st ill hav e considerab le access t o t h e dat a dict ionar y. St ar t list ing t he v iew s wit h : Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re SELECT view_name FROM all_views ORDER BY 1; Er r or han dling and except ions nt erUSER_ - pr ocess com muisnicat ions The v Iiew OBJECTS a r easonable st ar t ing point for look ing int o t he d at a d ict ion ary . Ther e is a r ow in t h is view f or ever yt hing w e creat e. A par t ial descr ipt ion is show n next : Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. SQL> desc user_objects Name Null? Type [ Team LiB ] ------------------------------ -------- --------------OBJECT_NAME VARCHAR2(128) OBJECT_TYPE VARCHAR2(18) CREATED DATE

[ STATUS Team LiB ] . . . .

VARCHAR2(7)

We can select a full list of ob ject n ames an d t h eir t yp es fr om t h is view . The ALL and DBA OBJECTS v iews in clu des an OWNER colum n. Th is perm it s u s t o see w ho ow ns w hat . To see all obj ect s t o w hich you hav e access an d w h o ow ns t hose obj ect s, y ou can ex ecut e t he f ollow ing qu er y —t his is a len gt hy out pu t an d in clud es all dat a dict ionar y obj ect s at y our d isposal.

SELECT object_type, object_name, owner, created, status FROM all_objects ORDER BY 1; •

Table of Content s

Pr ogrD am m ing Or aapt cl e ® s and Stor e dsP troce Thirsee d Ediwtiit on The DL in Ch er Tr4i gger cr eat es object h atdure w e s,can h

t he follow in g:

By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

SQL> SELECT object_type, object_name I SBN: 0- 13 -0 850 33 -0 2 FROM user_objects ORDER BY 1 DESC; Pages: 44 8

OBJECT_TYPE OBJECT_NAME ------------------ ----------------------TABLE COURSES Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t TABLE PARKING_TICKETS Kevin SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d TABLE Ow ens ex plor es PL/ PROFESSORS tTABLE eaches you w hat y ou nSTUDENTS eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. TABLE STUDENT_VEHICLES Using r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake TABLE easy- t o- follow inst STUDENTS_COURSES adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our TABLE STATE_LOOKUP dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he INDEX PK_COURSES bu sin ess evolv es. Topics cov er ed include: INDEX UK_STUDENTS_LICENSE INDEX PK_PARKING_TICKETS INDEX PK_PROFESSORS View in g const r aint s in t h e dat a dict ion ar y INDEX PK_STATE_LOOKUP INDEXCom plex r ule enf orcem PK_STUDENTS en t INDEX PK_STUDENTS_COURSES INDEXPL/ SQL p r ogr am un PK_STUDENT_VEHICLES it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Con cept u ally , t he USER_OBJECTS view is a par ent t o ot h er view s t hat cont ain sp ecific inf ormEratr or ionhan abou t t hand e objexcept ect s wions e cr eat e. Two v iew s of p art icular in t er est ar e: USER_ TABLES dling and USER_ SEQUENCES. I nt er - pr ocess com mu nicat ions A r ow at in ivUSER_ OBJECTS, for an obp ject ofy tkyey pe, TABLE, eans e is r ow in m uch Declar e const r aint s, including rim ar u nique,mf or eignt hker ey, chaeck , and USER_TABLES. Th e USER_TABLES r ow w ill h ave m or e specif ic inf orm at ion abou t t h at m or e t able. Th e follow ing quer y join s t hese t w o v iew s. I t select s t he colum n CREATED fr om Pr ogr USER_OBJECTS am m ing Oracle Tr igger and or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce plus insfor m atStion f r om USER_TABLES. for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] SELECT user_objects.created, user_tables.table_name, user_tables.tablespace_name

[ Team FROM LiB ] user_objects, user_tables WHERE user_objects.object_name = user_tables.table_name;

The r esult f r om t his q uery , f or t h e STUD ENTS schema, is show n next .

CREATED TABLE_NAME --------------- ---------------------18-jul-03 17:45 COURSES 18-jul-03 17:45 PARKING_TICKETS • Table of Content s 18-jul-03 17:45 PROFESSORS Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d 18-jul-03 17:45 STATE_LOOKUP 18-jul-03 17:45 STUDENTS By Kevin Owens 18-jul-03 17:45 STUDENTS_COURSES 18-jul-03 17:45 STUDENT_VEHICLES

TABLESPACE_NAME ------------------STUDENT_DATA STUDENT_DATA STUDENT_DATA Edi ti on STUDENT_DATA STUDENT_DATA STUDENT_DATA STUDENT_DATA

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

AI SBN: r ow 0in13USER_ for an ob ject of t y pe SEQUENCE, means t here is a r ow in -0 850 33OBJECTS, -0 USER_SEQUENCES. The f ollow ing qu er y j oins t h ese t w o view s w her e t he OBJECT_ TYPE Pages: 44 8 = SEQUENCE.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t KevinSELECT Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches FROM you wuser_objects, hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. user_sequences Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake WHERE user_objects.object_name = adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our user_sequences.sequence_name; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: [ Team LiB ] View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

5.3 Constraint Views Ther e ar e t w o d at a d ict ionar y v iews t hat pr ovid e you d et ailed in for m at ion ab out con st raint s. These ar e USER_CONSTRAI NTS and USER_ CONS_COLUMNS. A t able can h ave no const r aint s, or man y. For ev ery con st r aint in a t able t here is a r ow in USER_CONSTRAI NTS t h at d escrib es t hat par t icu lar con st rain t , including t h e t able n ame t o w hich t hat con st r aint is app lied. I f y ou k now a con st raint nam e an d y ou w ant t o k now t he const r ain t t yp e, q uer y USER_CONSTRAI NTS. This v iew descr ibes t he con st r aint defin it ion . I t does n ot pr ov ide y ou w it h t h e colu m n n am e( s) on w h ich t hat const r ain t is d ef ined. •The USER_CONS_ Table ofCOLUMNS Content s view show s t he colum ns in a const r aint . I f a pr imar y k ey is a concat eye ® , tTr her e wsilland beStor t w eod row s dure for ts,h at const r aint in t h is view . Each colum n in t h e Pr ogr amenat m inged Ork a cl i gger P roce Thir d Edi ti on concat enat ed p r im ar y k ey con st raint w ill hav e a row , an d each r ow w ill diff er by By Kevin Owens POSI TI ON—t his in dicat es t he posit ion of a colum n w it h r esp ect t o concat enat ed colu m n const r ain t s. Pub lish er: Prent ice Hall PTR

The f ollow in g t able high lig ht s t h e join in g colum n s of t hese view s. USER_CONSTRAI NTS and Pub Dat e: Decem ber 0 5, 2 003 USER_CONS_COLUMNS each h ave t he colum n CONSTRAI NT_NAME an d TABLE_NAME. I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

USER_CONSTRAINTS CONSTRAINT_NAME

USER_CONST_COLUMNS CONSTRAINT_NAME

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t CONSTRAINT_TYPE TABLE_NAME Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d COLUMN_NAME t TABLE_NAME eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. POSITION Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our ab ases [dat Team LiBt o ] incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

5.4 USER_CONS_COLUMNS The USER_CONS_ COLUMNS t ells y ou w hat colu mn s m ake up t he const r aint . D et ails ab out t he const r ain t , such as w het her it is a CHECK or UNI QUE con st r aint , ar e in USER_ CONSTRAI NTS. The SQL* Plu s descr ibe of t h e t able is t h e follow ing.

SQL> DESC user_cons_columns •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d Null? P roce dure s, Type Thir d Edi ti on Name ---------------------------------------------------By Kevin Owens OWNER NOT NULL VARCHAR2(30) CONSTRAINT_NAME NOT NULL VARCHAR2(30) TABLE_NAME NOT NULL VARCHAR2(30) Pub lish er: Prent ice Hall PTR COLUMN_NAME VARCHAR2(4000) Pub Dat e: Decem ber 0 5, 2 003 POSITION NUMBER I SBN: 0- 13 -0 850 33 -0

Pages: 44 8

OWNER

This is t he ow ner of t h e t able in w hich t h e const r ain t is enf or ced.

CONSTRAINT_NAME isage t he com namplex e u sed t he DD use tSy h is nam eand t o ALTER or DROP Ef fect ively creat e an dThis man dat in abases w itL.h You Or acle! st ems dat ab ase ex per t t hePL/ con st r aint . I f t here r aint specif ied in tage he D( SQL) DL, , an d Kevin Ow ens ex plor es SQL, Or acle's answisernot oconst t h e St r uctnam ur ede Query Langu Ornacle st rrob aintust w itan h da com for mplex at sim t o SYS_ follow ed by t eaches you w hat y ou eed cr t oeat knes owt he t o con build datilar ab ases f or C y our b usiness. a u niqu e sequ en ce of digit s. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake TABLE_NAME n am of t he t hatand hassttored h e const r ainur t . es- f eat u r es t hat allow y our adv ant ag e of Or acle The feat ur es esuch as ttab rigle gers pr oced dat ab ases t o incor por at e is but siness r ules hich t or aint man. age and m odif y as t he COLUMN_NAME This he colum n nw am e ofart e heeasy const bu sin ess evolv es. Topics cov er ed include: POSITION This ap plies t o t h e con cat en at ed p rim ar y k ey , u nique, an d f or eign k eys. Ou r STUD ENT D DL cr eat es a concat enat ed uniq ue const r aint on colum ns View in g const r aint the dict ionan ardy LI CENSE. For t his const r ain t , t h er e ar e t w o for sa in st ud endat t 's aSTATE colum ns an d t w o r ows in t h is view . The row in t h is v iew , f or t his Com plex r ule enf orcem const r ainen t ,t w ill hav e POSI TI ON= 1 for STATE an d POSI TI ON= 2 for LI CENSE. PL/ SQL p r ogr am un it s and langu age f eat u res [ Team DatLiB a t y] pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

5.5 USER_CONSTRAINTS The USER_CONSTRAI NTS view d escrib es con st r aint t y pes and det ail at t ribu t e inf orm at ion on const r ain t s. When diagn osin g an Or acle const rain t v iolat ion er r or m essage w it h a g en er ic Or acle- g en er at ed con st raint nam e, such as SYS_C0 123 45, you look her e t o det er m ine t h e t y pe of const r aint . I f it is a FOREI GN KEY, t hen you m ight cont inu e you r sear ch for t h e t able nam e an d colum n nam e of t h e par en t . I f it is a CHECK const r aint , t h en y ou m ig ht look at t h e SEARCH_COND I TI ON t o d et er m ine t h e r ule of t he CHECK con st raint . When t hese st ep s ar e t ak en , y ou may lik ely look at USER_ CONS_COLUMNS, u sing t h e const rain t n ame, t o det er min e t he ex act colum n n am e( s) on w h ich t he con st r aint is defin ed . The d escr ip t ion of t his v iew is: •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

SQL> user_constraints PubDESC lish er: Prent ice Hall PTR Name Null? Type Pub Dat e: Decem ber 0 5, 2 003 ------------------------------ -------- ---------------I SBN: 0- 13 -0 850 33 -0 OWNER NOT NULL VARCHAR2(30) Pages: 44 8 CONSTRAINT_NAME NOT NULL VARCHAR2(30) CONSTRAINT_TYPE VARCHAR2(1) TABLE_NAME NOT NULL VARCHAR2(30) SEARCH_CONDITION LONG Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t R_OWNER VARCHAR2(30) Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er tVARCHAR2(30) o t h e St r uct ur ed Query Langu age ( SQL) , an d R_CONSTRAINT_NAME tDELETE_RULE eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. VARCHAR2(9) STATUS VARCHAR2(8) Using easy- t o- follow inst r uct ions an d ex am ples, VARCHAR2(14) t his book pr esent s t echniq ues t o t ake DEFERRABLE adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our DEFERRED VARCHAR2(9) dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he VALIDATED VARCHAR2(13) bu sin ess evolv es. Topics cov er ed include: GENERATED VARCHAR2(14) BAD VARCHAR2(3) RELY VARCHAR2(4) View in g const r aint s in t h e dat a dict ion ar y LAST_CHANGE DATE Com plex r ule enf orcem en t The colum ns pOWNER, NT_NAME, and TABLE_NAME hav e t h e same meaning as t he PL/ SQL r ogr am CONSTRAI un it s and langu age f eat u res v iew USER_CONS_ COLUMNS. See t he follow ing : Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] CONSTRAINT_TYPE

This sing le ch aract er is t h e con st rain t t y pe. C– NOT NULL or CHECK P– Pr im ar y Key U– Un ique R– For eign Key

SEARCH_CONDITION

This st or es t he r u le of a CHECK const r aint ; for ex am ple, " ( AGE < 12 5) . " For a NOT NULL const r aint , t h e v alu e is " CHECK OR NOT NULL. "

A f or eig n k ey const rain t m ust ref er ence a colum n t hat has a pr im ary k ey or uniq ue const r aint . Th at colum n can be in t h e t able of an ot her sch em a. I n t h is case, t he colum n ident if ies t h at schem a ow ner . I f t he • Table of Content s t able is n ot in anot h er schem a, t h is valu e eq uals t h e cu rr ent sch em a. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on This v alue is on ly set for a for eign key const r aint , or w hen By Kevin Owens CONSTRAI NT_ TYPE = R. R_OWNER

R_CONSTRAINT_NAME This v alue is on ly set for a for eign key const r aint , or CONSTRAI NT_ TYPE = R. Th is colu mn ident if ies t he r eferenced Pub lish er: Prent ice Hall PTR im ary key or u niqu e con st raint . A f or eign k ey m ust alw ay s Pub Dat e: Decem ber 0 5, 2pr 003 r ef erence a colu mn w it h a p rim ar y k ey or uniq ue const r ain t . Th is I SBN: 0- 13 -0 850 33 -0 v alue is not t hat colum n n am e, but r at her t he con st r aint nam e. Pages: 44 8

DELETE_RULE

This is on ly set w hen t he const r ain t is a for eign key . Values f or t his ar e:

CASCAD E: The f or eig n k ey w as creat ed w it h t h e DELETE Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t CASCAD E r u le. Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou nNO eedACTI t o kn ow t o build ust an d com plex w dat asesinf or b usiness. ON: Norob D ELETE CASCADE asab used t h ey our for eign key defin it ion . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake STATUS This equ als ENABLED DI SABLED. adv ant ag e of Or acle feat ur es such as t rig gersorand st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he DEFERRABLE DEFERRABLE or NOT DEFERRABLE. bu sin ess evolv es. Topics cov er ed include: DEFERRED This is I MMEDI ATE or DEFERRED . I MMED I ATE is t h e defau lt . DEFERRED only ap plies t o D EFERRABLE con st r aint s. Th is is View in g const r aintDEFERRED s in t h e datifa t dict ion ar y he DEFERRABLE con st rain t is d eclar ed I NI TI ALLY DEFERRED or if it is set t o I NI TI ALLY DEFERRED t hr oug h an ALTER Com plex r ule enf orcem en t TABLE st at em en t . PL/ SQL p r ogr am un and rlangu age eat u res VALIDATED I f ita sconst aint is en fabled w it h t he NOVALI DATE opt ion, t his colum n w ill be set t o NOT VALI DATED, ot her wise it is VALI DATED. Dat a t y pes and comp osit e st r u ct u re GENERATED Set t o GENERATED for Or acle- gener at ed const r aint nam es. Set t o Er r or han dling and except ions f or user - generat ed nam es. USER_NAME BAD I nt er - pr ocess comAmu YES indions icat es t h at t h e const r ain t specifies a cent ur y in an nicat am bigu ous m ann er . Th is can be avoided w it h pr oper use of TO_ CHAR Declar at iv e const rfu aint ncts,ions. including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e RELY I ndicat es w het her a con st raint is enf orced or unenf or ced. Pr ogr am m ing Oracle TrThe iggerlast s and St or edconst Pr oced ur es , Then ir dabled Ed it.ion , is an inv aluable r esou rce LAST_CHANGE t ime t he r aint was for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly INDEX_OWNER int ellig en t , com plex datThe abases. ow n er of t he ind ex if t h e const r ain t is a pr im ary k ey or u nique const r ain t . [ Team LiB ] INDEX_NAME The n am e of t he ind ex . [ Team LiB ]

[ Team LiB ]

5.6 Data Dictionary Constraint Scripts 5.6.1 Constraints on a Table The f ollow in g q uer y is a g en er al scr ip t t o qu er y t h e con st rain t s of a t ab le. The use of t h e scr ipt accept s a t ab le nam e as a com m and line ar gu ment .



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

SQL> @my_const_are table_name By Kevin Owens

Follow ing t h e scr ipt t ext is t he SQL* Plu s out pu t f r om t he STUDENTS t able. Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

-- Filename: my_const_are.sql set verify off column column_name format a15plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Ef fect ively creat e an d man age com column Kevin Owtable_name ens ex plor esformat PL/ SQL,a12 Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d set pagesize 1000 t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. SELECT SUBSTR(A.column_name,1,30) column_name, DECODE(B.constraint_type, Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 'PRIMARY adv ant ag e of'P', Or acle feat ur esKEY', such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o'U', incor'UNIQUE por at e buKEY', siness r ules w hich ar e easy t o man age and m odif y as t he 'C', ORerNOT NULL', bu sin ess evolv es. 'CHECK Topics cov ed include: 'R', 'FOREIGN KEY') constraint_type, A.constraint_name in g const r aint s in t h eA,dat a dict ion ar y FROM View user_cons_columns user_constraints B plex r ule enf orcem en t WHERECom A.table_name = UPPER('&1') AND A.table_name = B.table_name SQL p r ogr am un it s and age f eat u res AND PL/ A.constraint_name = langu B.constraint_name AND a.owner = b.owner Dat a t y pes and comp osit e st r u ct u re ORDER BY 2 DESC; clearEr columns r or han dling and except ions I nt er - pr ocess com mu nicat ions The scr ipt f ile nam e is MY_ CONST_ARE. SQL. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly SQL> int ellig@my_const_are en t , com plex datstudents abases. COLUMN_NAME [ Team LiB ] --------------STATE LICENSE_NO

CONSTRAINT_TYPE ----------------UNIQUE KEY UNIQUE KEY

CONSTRAINT_NAME ----------------------UK_STUDENTS_LICENSE UK_STUDENTS_LICENSE

STUDENT_ID [ Team LiB ] STATE STUDENT_ID STUDENT_NAME COLLEGE_MAJOR STATUS

PRIMARY KEY FOREIGN KEY CHECK OR NOT CHECK OR NOT CHECK OR NOT CHECK OR NOT

NULL NULL NULL NULL

PK_STUDENTS FK_STUDENTS_STATE SYS_C002073 SYS_C002074 SYS_C002075 SYS_C002076

All t h e con st rain t nam es t h at begin w it h SYS ar e NOT NULL const r aint s. As descr ibed in Ch apt er 3, an Or acle er r or m essage on t hese const r aint s in clu des t he t able nam e and colum n nam e.

5.6.2 Chasing a Constraint Name •You can inv est Table igatofeContent a par t sicu lar con st rain t by joining t h e t able an d colum n nam e, fr om Pr ogr am m ing Or a cl e ® Tr i gger and Storhe d dure s, Thir on st raint USER_CONS_COLUMNS v siew , wit t hPeroce definit ion ofd tEdi heticon

f rom t he v iew USER_CONSTRAI NTS. The follow in g quer y is used t o det erm ine t his inf orm at ion . I f you w ere By Kevin Owens giv en a const rain t w it h a SYS_ C t y pe nam e, t his SQL w ould r et ur n t he t ab le nam e, colum n nam e, and const r aint definit ion. Follow ing t he list ing is t he SQL* Plu s session t o inv est igat e t w oPub con ster: r aint s:icet he rof essor check const rain t an d a SYS n amed const rain t . lish Prent HallpPTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

-- Filename: i_am.sql set verify off Ef fect ively creat e an d man age com column column_name format a15plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Owtable_name ens ex plor esformat PL/ SQL,a12 Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d column t eaches you w hat y ou n eed format t o kn ow a20 t o build rob ust an d com plex dat ab ases f or y our b usiness. column constraint_name SELECT user_constraints.constraint_name, Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake user_cons_columns.table_name, adv ant agSUBSTR(user_cons_columns.column_name,1,30) e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he column_name, bu sin essDECODE(user_constraints.constraint_type, evolv es. Topics cov er ed include: 'P', 'PRIMARY KEY', 'U', 'UNIQUE KEY', View in g const r aint s in t h e dat a dict ion ar y 'C', 'CHECK OR NOT NULL', 'R', 'FOREIGN KEY') constraint_type Com plex r ule enf orcem en t FROM user_cons_columns, user_constraints WHEREPL/ user_constraints.constraint_name = upper('&1') SQL p r ogr am un it s and langu age f eat u res and user_constraints.owner=user_cons_columns.owner and Datuser_constraints.constraint_name= a t y pes and comp osit e st r u ct u re user_cons_columns.constraint_name; clearEr columns r or han dling and except ions I nt er - pr ocess com mu nicat ions The f ollow in g sh ows t he d ef init ion of a check con st r aint . The f ile n am e is I _AM. SQL. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig@i_am en t , com plex dat abases. SQL> ck_professors_tenure [CONSTRAINT_NAME Team LiB ] TABLE_NAME COLUMN_NAME CONSTRAINT_TYPE -------------------- ---------- ----------- ----------------CK_PROFESSORS_TENURE PROFESSORS TENURE CHECK OR NOT NULL

[The Team n ex LiB t ex ]am ple t ells us t his is a CHECK or NOT NULL const r aint on t he STUDENTS STATUS colum n.

SQL> @i_am SYS_C002633 CONSTRAINT_NAME TABLE_NAME COLUMN_NAME CONSTRAINT_TYPE ------------------ ----------- ----------- ----------------SYS_C002633 STUDENTS STATUS CHECK OR NOT NULL

5.6.3 CHECK Constraint Rule •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

A NOT NULL const rain t is a t y pe of CHECK const r aint . Som et im es w e need t o mak e t h is By Kevin Owens det er min at ion . The NOT NULL const r ain t is a st andar d defin it ion , bu t if t he ru le is a com plicat ed CHECK enf orcem en t , w e need t o inv est ig at e. The r ule f or a check const r ain t is in t he SEARCH_ CONDI TI ON colum n of t he USER_CONSTRAI NTS view . The next qu er y r et ur ns lishfor er: Prent ice Hall PTR t he Pub ru le a check con st r aint . Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

-- Filename: my_rule_is.sql set verify off Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t set arraysize 1 Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d set long 75 t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. SELECT search_condition FROM user_constraints Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake WHERE = such upper('&1'); adv ant agconstraint_name e of Or acle feat ur es as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: The f ollow in g r et ur ns t he r ule f or t he ch eck const r aint : CK_PROFESSORS_ TENURE View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t SQL> PL/ @my_rule_is ck_professors_tenure SQL p r ogr am un it s and langu age f eat u res SEARCH_CONDITION Dat a t y pes and comp osit e st r u ct u re -----------------------------------------Er r or dling and except ions tenure IN han ('YES','NO') I nt er - pr ocess com mu nicat ions You can select just you r check con st r aint s by f ilt er ing on t he GENERATED colum n. A ivee generat const r aint p rim ar ycolum k ey , nu nique, or eign k ey, ch eck , and m uch const rDeclar ain t nat am ed s, byincluding Or acle h as t his set t o "fGENERATED NAME. " Const rain t s m or e y ou n am e hav e t his colum n set t o " USER NAME." Pr ogrf ollow am m in ing Oracles Tr igger s and St or ed Prnam oced es , check Th ir d con Ed itst ion , is an inv aluable r esou rce The g select t he t able, const r aint e,urand r aint r ule. for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] set pagesize 0 SELECT 'T='||TABLE_NAME||' '||

'C='||CONSTRAINT_NAME, [ Team LiB ] SEARCH_CONDITION FROM USER_CONSTRAINTS WHERE GENERATED='USER NAME' AND CONSTRAINT_TYPE='C';

The r esult s f rom t his ar e:

T=PROFESSORS C=CK_PROFESSORS_SALARY salary < 30000 •T=PROFESSORS Table of Content s C=CK_PROFESSORS_DEPARTMENT Pr ogr am m ing OrIN a cl e('MATH','HIST','ENGL','SCIE') ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on department By Kevin Owens

T=PROFESSORS C=CK_PROFESSORS_TENURE tenure IN ('YES','NO') Pub lish er: Prent ice Hall PTR

T=STUDENTS C=CK_STUDENTS_ST_LIC Pub Dat e: Decem ber 0 5, 2 003 (stateI SBN: IS 0-NULL AND 13 -0 850 33 -0license_no IS NULL) OR (state IS NOT NULL AND Pages: 44 8 T=STUDENTS C=CK_STUDENTS_STATUS status IN ('Degree','Certificate') Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eachesQuerying 5.6.4 you w hat y ou Parent n eed t o Tables kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easyfollow instar uct ex am ples, t his book pr t echniq o for t ake The f ollow intgo-SQL does selfions - joinan ond USER_CONSTRANTS t oesent det ersmin e parues en t tin m at ion. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o tincor por at e butsiness r ules w hich ar e easy t o man age and m odif y as t he To illust r at e, he COURSES able has a f oreign k ey called: bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t FK_COURSES_ST_ID PL/ SQL p r ogr am un it s and langu age f eat u res This const ill appear in tehestcolum n CONSTRAI NT_ NAME. Th is sam e r ow w ill h ave t he Dat a r taint y peswand comp osit r u ct u re follow ing colum n v alues: Er r or han dling and except ions R_TABLE_NAME t ableions nam e of t h e par ent . I nt er - pr ocess comThe mu nicat R_CONSTRAINT_NAME e of t he pprim rimar aryy kkey ey, or uniq ue hat f oreign Declar at iv e const rThe aint ns,am including u nique, f orconst eign rkain ey,t tch eckt he , and m uchk ey r ef erences. m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. -- Filename: my_parents_are.sql [set Team LiB ] off verify column foreign_key format a30 heading 'foreign key' column parent_table format a12 heading 'parent|table' column parent_key format a17 heading 'parent key'

SELECT a.constraint_name|| [ Team LiB ] SUBSTR(DECODE(a.delete_rule,'NO ACTION','(N)', 'CASCADE','(C)'),1,3) foreign_key, b.table_name parent_table, a.r_constraint_name parent_key FROM user_constraints a, user_constraints b WHERE a.table_name = upper('&1') AND a.r_constraint_name = b.constraint_name; clear columns SQL> @my_parents_are students_courses parent foreign key table parent key ------------------------------ --------------------------FK_STUDENTS_COURSES_ST_ID(N) STUDENTS PK_STUDENTS • Table of Content s FK_STUDENTS_COURSES_COURSE(N) COURSES PK_COURSES Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on FK_STUDENTS_COURSES_PROF(N) PROFESSORS PK_PROFESSORS By Kevin Owens

How w ould y ou det er m ine t h e t able colum n nam e t h at is r efer en ced by a for eig n key Pub lish er: Prent ice Hall PTR const r ain t ? You k now t he n ame of t he f oreign k ey const r aint . What is t he p arent colum n namPub e? Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Qu er y USER_ CONSTRAI NTS u sin g t he for eign k ey const r aint nam e. Not e t h e valu es of R_TABLE_NAME and R_ CONSTRAI NT_NAME. Ef fectQu ively e an d man age com plex w it h Or acle! an SydstR_CONSTRAI ems and dat ab ase ex per t er ycreat USER_ CONS_COLUMNS u sindat g t abases he R_ TABLE_ NAME NT_ NAME. Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d Notyou e t hw e hat valuye( COLUMN_ an d POSI t eaches ous)nof eed t o kn ow NAME t o build rob ust TI anON. d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 5.6.5 Querying Child Tables dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: This scr ip t is sim ilar t o t h e par ent scr ipt f r om earlier . I t d oes a self - join on USER_CONSTRAI NTS. To find a child t able, look f or a const r aint nam e in t he CONSTRAI NT_ NAME colum h at View in g const r aint s innt.hThen e dat alook dictfor ion tar y sam e nam e elsew her e in t he colum n R_ CONSTRAI NT_NAME—at t h at r ow t he v alue of CONSTRAI NT_ NAME is a f oreign k ey . Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re -- Filename: my_children_are.sql Er r or han dling and except ions set verify off column parent_key format a15 I nt er - pr ocess com mu nicat ions column child_table format a16 column child_key format a28 Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch SELECT a.r_constraint_name parent_key, m or e a.table_name child_table, a.constraint_name|| Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce SUBSTR(DECODE(a.delete_rule,'NO for dat abase d ev elopers, d esign er s, and pr oj ectACTION','(N)', leader s look in g t o b uild an d m aint ain t r uly 'CASCADE','(C)'),1,3) child_key int ellig en t , com plex dat abases. FROM user_constraints A, user_constraints B [ Team LiB ] WHERE B.table_name = upper('&1') AND a.r_constraint_name = b.constraint_name ORDER BY a.table_name;

clear [ Team columns LiB ]

Sam ple quer y:

SQL> @my_children_are state_lookup PARENT_KEY --------------PK_STATE_LOOKUP PK_STATE_LOOKUP •

CHILD_TABLE ---------------STUDENTS STUDENT_VEHICLES

CHILD_KEY --------------------------FK_STUDENTS_STATE(N) FK_STUDENT_VEHICLES_STAT(N)

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

5.6.6 Constraint Status By Kevin Owens You can check t he ENABLE/ D I SABLE st at u s of a const r aint . The f ollow ing disables t he pr imar y Prent ice Hall PTR k ey Pub in lish t h eer:STUD ENTS t ab le, p lus all f or eign k ey con st rain t s t hat r ef er ence t h at k ey. Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

ALTER TABLE students DISABLE CONSTRAINT pk_students CASCADE; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin ensconst ex plor es t PL/ Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d To seeOw w hat rain s arSQL, e disabled: t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin esstable_name, evolv es. Topics cov er ed include: status SELECT constraint_name, FROM user_constraints WHERE status='DISABLED' View in g const r aint s in t h e dat a dict ion ar y The r esult is: r ule enf orcem en t Com plex PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re TABLE_NAME CONSTRAINT_NAME STATUS Er r or han dling and except ions ---------------- ------------------------- -------STUDENTS PK_STUDENTS DISABLED I nt er - pr ocess com mu nicat ions STUDENTS_COURSES FK_STUDENTS_COURSES_ST_ID DISABLED Declar at iv e const r aint s, including p rim ar y k ey ,DISABLED u nique, f or eign k ey, ch eck , and m uch STUDENT_VEHICLES FK_STUDENT_VEHICLES_STUD m or e Pr ogrp am Tr igger s and Pr ocedwur Thfollow ir d Edinit g: ion , is an inv aluable r esou rce The r imm aring y k Oracle ey t o STUDENTS canStbor e ed en abled it hest ,he for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] SQL> ALTER TABLE students ENABLE CONSTRAINT pk_students;

Table [ Team altered. LiB ] The f or eig n k ey const r ain t s ar e st ill disabled . They h ave t o be enab led ind iv idu ally .

SELECT table_name, constraint_name, status FROM user_constraints WHERE status='DISABLED'

The r esult is:



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

TABLE_NAME CONSTRAINT_NAME ---------------- ------------------------STUDENTS_COURSES Pub lish er: Prent ice HallFK_STUDENTS_COURSES_ST_ID PTR STUDENT_VEHICLES FK_STUDENT_VEHICLES_STUD Pub Dat e: Decem ber 0 5, 2 003

STATUS -------DISABLED DISABLED

I SBN: 0- 13 -0 850 33 -0 8 t s can be enabled w it h : These Pages: const 44 r ain

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER students_courses t eachesTABLE you w hat y ou n eed t o kn owENABLE t o buildCONSTRAINT rob ust an d com plex dat ab ases f or y our b usiness. fk_students_courses_st_id; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake ALTER TABLE student_vehicles ENABLE CONSTRAINT adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he fk_student_vehicles_stud; bu sin ess evolv es. Topics cov er ed include:

5.6.7View Validated in g const r aint s in

t h e dat a dict ion ar y

Comaplex r ule enf orcem t h du plicat e values in t he p r im ar y k ey colu mn . This is causing We h ave t able called TEMPen w it som e hav oc in t he sy st em . The fir st t ask is t o descr ibe t h e t able an d check t he st at u s of t he p r ogr am un and langu f eat u res const rPL/ ainSQL t s. One possib ilititys is t hat t he age const r aint is D I SABLED. Dat t y pes and comp The ex amaple t able d escr ip tosit ion eis:st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch SQL> desc temp m or e Name Null? Type Pr-------------------------------ogr am m ing Oracle Tr igger s and St or ed -------Pr oced ur es--------------, Th ir d Ed it ion , is an inv aluable r esou rce TEMP_ID NUMBER(3) for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly TEMP_DESC VARCHAR2(20) int ellig en t , com plex dat abases. [ Team LiB ] We check t he st at u s and last t im e chan ge of t he con st r aint .

[ Team LiB ] SELECT table_name, constraint_name, status, last_change FROM user_constraints WHERE table_name='TEMP' AND constraint_type='P';

The con st r aint is ENABLED. Th e LAST_CHANGE t im e can t ell us if t h is con st raint has recen t ly been enab led and r een abled.

TABLE_NAME CONSTRAINT_NAME STATUS LAST_CHANGE •-------------Table of-----------------Content s -------- -----------Pr ogr am m ing Or a cl e ®PK_TEMP Tr i gger s and Stor e d P roceENABLED dure s, Thir d 07-aug Edi ti on TEMP 21:27 By Kevin Owens

The con st r aint is enabled but t her e ar e dup licat es. This h as t o b e a d ef err able const r aint . Dat a aser:loaded t he const r aint w as en abled w it h t he NOVALI DATE opt ion. We can ver if y Pubwlish Prent iceand Hall PTR t his Pub w itDat h te:h eDecem follow ing: ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

SELECT table_name, constraint_name, deferred, Ef fect ively creat e an ddeferrable, man age com validated plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t FROM Kevin Owuser_constraints ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d WHERE t eachesdeferrable='DEFERRABLE'; you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake The r esult r om his is t he ollow ingas : t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our adv ant ag e fof Or tacle feat urfes such dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y TABLE_NAME CONSTRAINT DEFERRED DEFERRABLE VALIDATED Com plex---------r ule enf orcem en t ------------------------------- ------------TEMP PK_TEMP IMMEDIATE DEFERRABLE NOT VALIDATED PL/ SQL p r ogr am un it s and langu age f eat u res a t y pes and comp st r uectar u re The pDat r oblem need s corr ect osit ion .eTher e du plicat es an d t hey mu st be rem ov ed . We can use an EXCEPTI ONS t able as descr ibed next : Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e SQL> desc exceptions PrName ogr am m ing Oracle Tr igger s and St or ed Null? Pr oced ur esType , Th ir d Ed it ion , is an inv aluable r esou rce -------------------------------------------------for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly ROW_ID ROWID int ellig en t , com plex dat abases. OWNER VARCHAR2(30) VARCHAR2(30) [ TABLE_NAME Team LiB ] CONSTRAINT VARCHAR2(30)

You can enab le t he const r aint using t he ex cept ion s t able. The offend ing r ows are record ed in

t[ he EXCEPTI Team LiB ] ONS t able. You should delet e any exist ing r ow s in t he ex cept ion s t able f ir st .

SQL> ALTER TABLE temp ENABLE CONSTRAINT pk_temp 2 EXCEPTIONS INTO EXCEPTIONS; ORA-02437: cannot validate (SCOTT.PK_TEMP) - primary key violated

The EXCEPTI ONS t able has each r ow t hat is a dup licat e. First , let ' s quer y t he pr oblem t able. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

SQL> *iceFROM temp; PubSELECT lish er: Prent Hall PTR Pub Dat e: Decem ber 0 5, 2 003

TEMP_ID TEMP_DESC I SBN: 0- 13 -0 850 33 -0 ---------- -----------------Pages: 44 8 1 Record One 1 Record Two 3 Record Three 4 Record Four Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches youallw that y ou t o kneow t os build rob ust anect d ed. comAplex dat ab ases f or y our b usiness. For t his sm ab le, t hneeed du plicat row ar e easily det lar ger t able w ould r eq uir ea join of EXCEPTI ONS an d TEMP: Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SELECT temp_id,temp_desc in g const r aint s in t h e dat a dict ion ar y FROM View temp, exceptions WHERE temp.rowid=exceptions.row_id; Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res The r esult f r om t his q uery is: Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions TEMP_ID TEMP_DESC -------------------------Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch 1 Record One m or e 1 Record Two Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Theellig t able b eplex corrdat ectabases. ed w it h an upd at e chang in g TEMP_I D t o " 2 " f or " Recor d Tw o. " Once int en t ,can com t his is done all colum n v alu es w ill be un ique. The next st ep is t o set t he const r aint t o t he st at e VALI [ Team LiBDATE. ]

[ Team LiB ] UPDATE temp SET temp_id=2 WHERE temp_desc='Record Two'; ALTER TABLE temp ENABLE CONSTRAINT pk_temp;

The con st r aint is enabled and validat ed. To r eru n t he af orem ent ioned quer y:

SELECT table_name, constraint_name, deferred, deferrable, validated FROM user_constraints WHERE deferrable='DEFERRABLE'; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

We seeOwens t hat t he con st r aint is VALI DATED . By Kevin

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

TABLE_NAME CONSTRAINT DEFERRED DEFERRABLE VALIDATED Pages: 44 8 ------------------- --------- -------------- ------------TEMP PK_TEMP IMMEDIATE DEFERRABLE VALIDATED

fect ively e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t [EfTeam LiBcreat ] Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Chapter Six. Row Trigger Mechanics 6. 1 I NTRODUCTI ON 6. 2 BEFORE VERSUS AFTER 6. 3 I NSERT ROW TRI GGER SYNTAX 6. 4 TRI GGER BODY 6. 5 EXAMPLE ROW TRI GGERS •

Table of Content s

Pr ogr am mA ing Or a cl e ® i gger s and Stor e d P roce dure s, Thir d Edi ti onNESS 6. 6 TABLE WITrTH ORACLE CONSTRAI NTS AND BUSI

RULES

By Kevin Owens

6. 6. 1 The Env iron m en t 6. 6. 2 The Pr ocedur al Const r ain t s t o Enf or ce

Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003

6. 6. 3 Befor e v er sus Af t er

I SBN: 0- 13 -0 850 33 -0 Pages:6.44 6.8 4 Using

Pack ages for Procedur al Const r aint s

6. 6. 5 Man aging Er r or Codes an d Messages 6. 6. 6 Tr igger Ar chit ect u re Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor Or acle's answ er t os.t hMost e St rex uct urples ed Query Langu ( SQL) , an d This chap t er cov er s es t hePL/ m SQL, echanics of r ow t r igger am are given w age it h I NSERT tt eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. r igger s. Row t rigg er s can fir e f rom I NSERT, UPDATE, and DELETE st at em ent s. Th e obj ect iv e is t o cov er t he mechanics of r ow t r igg er s f irst , an d t hen t reat diff er ences am ong inser t - r ow , Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake up dat e- r ow, and delet e- r ow t rigg er s. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases [ Team LiBt o ] incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

6.1 Introduction A t rigg er is a com piled p rocedur e st or ed in t he dat abase. The lan guag e you u se is PL/ SQL. You code and com pile a t r igg er in t h e same m an ner y ou code st or ed pr ocedu res. The follow ing is t he SQL* Plu s session t h at cr eat es and demon st rat es a sim p le I n ser t Row t r igger . This t r igg er calls DBMS_OUTPUT t o p r in t " ex ecut in g t em p_ air" for each r ow insert ed.

•SQL> set feedback Table of Content off s Pr ogr am m ing Or aTABLE cl e ® Tr i temp gger s and e d P roce dure s, Thir d Edi ti on SQL> CREATE (N Stor NUMBER); SQL> CREATE OR REPLACE TRIGGER temp_air By Kevin Owens 2 AFTER INSERT ON TEMP 3 FOR EACH ROW 4PubBEGIN lish er: Prent ice Hall PTR 5Pubdbms_output.put_line('executing temp_air'); Dat e: Decem ber 0 5, 2 003 6 END; I SBN: 0- 13 -0 850 33 -0 7 / Pages: 44 8 8 SQL> INSERT INTO temp VALUES (1); -- insert 1 row executing temp_air SQL> INSERT INTO temp SELECT * FROM temp; -- insert 1 row executing temp_air Ef fect ively creat e an dtemp man SELECT age com * plex dat abases it h inserts Or acle! Sy2st rows ems and dat ab ase ex per t SQL> INSERT INTO FROM temp; w-Kevin Ow enstemp_air ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d executing texecuting eaches you temp_air w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. SQL> Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ases t o incorst por e bu siness r ules t o even man age and odif he gle SQL Theab t hir d I NSERT at at ement insert ed t w owrhich ow s ar inteoeasy TEMP, t houg h tmhis w yasasa tsin bu sin ess evolv es. Topics cov er ed include: st at ement . Most in ser t SQL st at em en t s insert a sing le row ; how ever , as show n ear lier ,

m ult iple r ow s can be insert ed w it h one st at em en t . View [ Team LiBin]g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

6.2 Before versus After The in ser t of a sin gle r ow has t hr ee st ages. Figur e 6- 1 illust r at es each st age. Th er e ar e t w o st ages in w hich y ou can inj ect y our PL/ SQL cod e. The m iddle st ag e is t he Oracle const r aint enfor cement . The f irst st age is t h e ex ecu t ion of t he BEFORE- I NSERT t r ig ger. The t r igg er cod e at t his st age r un s BEFORE Oracle's const r aint en for cem ent and is called a BEFORE- I NSERTROW ( BI R) t r ig ger . You can w r it e code t h at ex ecut es AFTER Or acle' s const r ain t enf or cem en t . This is t he AFTER- I NSERT- ROW ( AI R) t rigg er .

Figu r e 6 - 1 . Row I nser t Tr i gge r . •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t From an in it ial look at Figur e 6- 1 it seem s t hat y ou can choose t o perf or m an operat ion t h at PL/ SQL p r ogr am un it s and langu age f eat u res execut es bef ore con st r aint enfor cement or af t er t he enf or cem en t . I n general, t his is t r ue. Dat a t y pes and comp osit e st r u ct u re Depend in g on w h at y ou wan t t o accom p lish you m ay b e requ ired t o p ut you r code in a befor e- const r ain t t rigg er , t he f ir st st ag e. For ex am ple, a t r igg er cod e t hat " ov er r ides colu mn " Er r or han dling and except ions v alues m ust ex ecut e in a BEFORE- I NSERT r ow t r igg er . I n som e sit u at ions, y ou m ay h ave a choiceI nt t oeru-se a bef ore aft er r ions ow t r igg er , b ut ch oose t he af t er t r ig ger because y ou w an t pr ocess comormu nicat y our code t o execut e af t er Or acle' s const r ain t enf or cem en t . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Each m t r igger or e in Figur e 6- 1 h as t he cap abilit y t o " see t he in ser t st at em ent colum n v alues. " This is a valuab le feat ur e. This f eat ur e allows a r ow t r igg er , f or exam p le, t o r aise an er ror if a colum n vmalue iolat esTraigger b usiness u le. Pr ogr am ing vOracle s and r St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Figur e en 6- 1t , sh ows t hedat p ossible int ellig com plex abases.t ask s t hat can b e per for m ed ( Task s Perf or med) for t he v ar iou s st ages of t he in ser t st at em ent . Th er e ar e t h ree st ages: BEFORE- I NSERT r ow t r igger [execut Teamion, LiB Or ] acle const r aint en for cem ent , and AFTER- I NSERT r ow t r igger ex ecut ion . The act ion t aken by Or acle' s const r aint en for cem ent is t o r aise an er r or or accep t t h e dat a. The Task Perf or med by ap plicat ion dev elop ed t r igger s f alls in t o t h ree g en er al cat egor ies:

Ov LiB err ide [ Team ] Colum n ( Bef ore Row Tr igger on ly) Reject Tr an sact ion ( Bef or e and Aft er Tr igg er ) Tak e Act ion ( Befor e or Aft er Tr igger ) " Ov err ide Colum n" ref er s t o a t r igg er ch anging t h e cont ent of a v alue fr om t he I NSERT st at ement . For ex am ple, a BI R t r igger can t r uncat e a valu e for a DATE colum n. Th is means t hat an I NSERT st at em ent t hat uses SYSD ATE in t h e st at em ent w ill hav e t hat v alu e t r uncat ed w hen it is insert ed in t he d at abase. " Rej ect t he Tr ansact ion, " in Figur e 6- 1 , r efer s t o t he app licat ion enfor cem ent of a com plex r ule. A com plex r ule is any r u le t hat is not easily or possibly enfor ced w it h an Or acle CHECK const r ain t an d can only b e enfor ced p rocedur ally . A t r igg er reject s an insert by calling t he bu ilt - in f unct ion RAI SE_APPLI CATI ON_ERROR. " in of Figur e 6-s1 , r efer s t o an y act ion t he t r igger m ay t ak e. This in clud es a pr int •" Tak e Act ion, Table Content w itogr h am DBMS_OUTPUT debu p ureposes. Rows,t rThir iggderEdi s tican Pr m ing Or a cl e ® Trfior gger s andg Stor d P roce dure on send signals t o ot her p rocesses using t he Or acle D BMS_ALERTS p ack age. Row t r igger s som et im es popu lat e global t emp orar y By Kevin Owens t ables w it h befor e an d af t er r ow v alu es for lat er u se b y aft er st at em ent lev el t r ig ger s. Ch apt er 7 con t in ues w it h t his t op ic in Sect ion 7. 4 , " Pr ocessing Row Capt u red Dat a. " Pub lish er: Prent ice Hall PTR

[ Team LiB ]

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

6.3 Insert Row Trigger Syntax The I n ser t Row t r igger h as t he f ollowin g sy nt ax .

CREATE OR REPLACE TRIGGER trigger_name AFTER|BEFORE INSERT ON table_name FOR EACH ROW •[WHEN (Boolean Table ofexpression)] Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, DECLARE Local By Kevin Owensdeclarations BEGIN Trigger Body written PL/SQL Pub lish er: Prent ice Hall PTR END;

Thir d Edi ti on

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 TRIGGER_NAME

Use t rig ger nam es t hat ident ify t he t ab le nam e and t r igger t y pe. A PL/ SQL r un t im e er ror will gener at e a PL/ SQL err or m essag e and r ef erence t h e t r igger nam e an d line num ber . The Ef fect ively d man age w it h OrI NSERT acle! Syrst ems and ,dat ase ex per t follow ing Orcreat acleeeran r or ind icat escom t h atplex Lin edat 5 abases in t h e AFTERow t r igger onab t he Kevin Ow ens ex plor es aPL/ answ STUDENTS t able, has divSQL, id e- bOr y-acle's zer o er r or. er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics er ed include: ORA-01476: divisor iscov equal to zero ORA-06512: at "SCOTT.STUDENTS_AIR", line 5 ORA-04088: error during execution of trigger View in g const r aint s in t h e dat a dict ion ar y 'SCOTT.STUDENTS_AIR' Com plex r ule enf orcem en t The cou ing pofr ogr lineam nuun mbiter s b eglangu ins atage t hef eat k eyw or d DECLARE. I f t here is no D ECLARE PL/nt SQL s and u res sect ion, t hen t he BEGI N st at ement is line nu m ber 1. Tr igg er nam es are f oun d in t he colu mn TRI GGER_NAME of USER_ Dat a t y pes and compTRI ositGGERS. e st r u ct uTr reigger n ames u sed in t his t ext ar e der ived fr om t h e t able n am e, t rig ger_ t yp e, and t r igger in g ev ent . Th e syn t ax is: Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch trigger_name m or e = table_name_[A|B] [I|U|D] [R|S] Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] trigger_name Tr igger nam es ar e lim it ed t o 30 ch ar act er s. You hav e t o ab br ev iat e t h e t able n am e t o ap pend t r ig ger at t r ibu t e infor m at ion. Long t able n am es should hav e a con sist ent abbr eviat ion . The t ab le nam e is used in t h e nam ing of f oreign k ey const r aint s and t r ig ger nam es. A consist en t abb rev iat ion shor t ens t he t r oub leshoot ing p rocess. [A|B]

I ndicat es t he BEFORE or AFTER par t of t he t r igger t y pe.

[I|U|D]

I ndicat es t he t rig gerin g ev en t . The t rig gerin g ev en t can be " I NSERT." I t can be " UPDATE." I t can be " I NSERT OR UPDATE OR DELETE. "

[R|S]

I ndicat es t he ROW or STATEMENT par t of t he t r igg er t yp e.

Ex am ples of t r igger nam es: •

Table of Content s

Taam ble gge r Ty pee d P roce dure s, Thir dTri Pr ogr m ing Or a cl e ® Tr Tri i gger s and Stor Edigge ti on ri ng By Kevin Owens STUDENTS

BEFORE EACH ROW

STUDENTS AFTER EACH ROW Pub lish er: Prent ice Hall PTR

STUDENTS AFTER STATEMENT

Ev ent

Tri gge r N a m e

I NSERT

students_bir

I NSERT OR UPD ATE

students_aiur

I NSERT

students_ais

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

AFTER|BEFORE Pages: 44 8 INSERT ON TABLE_NAME This clause t ells Or acle wh en t o ex ecut e t h e t r ig ger . I t can be BEFORE or AFTER Oracle's int egr it y const r aint ch eck s. You can designat e a BEFORE or AFTER t r igg er t o f ir e on m ult iple Efat st fect ement ively tcreat y pes,e exam an d man plesage ar e:com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor at e bu siness r ules w hich ar e easy t o man age and m odif y as t he BEFORE INSERT ORporUPDATE on table_name bu sin essINSERT evolv es.OR Topics cov er include:on table_name BEFORE UPDATE ORedDELETE AFTER INSERT OR DELETE on table_name View in g const r aint s in t h e dat a dict ion ar y Case logic in t he t rig ger bod y can isolat e a sect ion of code t o a p ar t icu lar SQL st at em ent . The Com plex r ule enf orcem en t Or acle packag e DBMS_ STAND ARD in clu des fou r fu nct ions t h at ar e int end ed f or t his p ur pose: PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions PACKAGE DBMS_STANDARD IS FUNCTION inserting RETURN I nt er - pr ocess com mu nicat ions BOOLEAN; FUNCTION updating RETURN BOOLEAN; FUNCTION VARCHAR2) BOOLEAN; Declar at iv eupdating const r aint(colnam s, including p rim ar y kRETURN ey , u nique, f or eign k ey, ch eck , and m uch FUNCTION deleting RETURN BOOLEAN; m or e etc, Pr ogrDBMS_STANDARD; am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce END for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. Use of t he af orem en t ioned fun ct ion s in an y cont ext ot h er t han a t r igg er b ody ev alu at es t o [ TeamYou LiBd] o not use t h e pack age nam e w h en r ef erencing t hese f unct ions. The follow ing NULL. illust rat es a t r igger u sing a CASE con st ru ct and t h e DBMS_STANDARD f un ct ion s.

[ Team LiB ] CREATE OR REPLACE TRIGGER temp_aiur AFTER INSERT OR UPDATE ON TEMP FOR EACH ROW BEGIN CASE WHEN inserting THEN dbms_output.put_line ('executing temp_aiur - insert'); WHEN updating THEN dbms_output.put_line ('executing temp_aiur - update'); END CASE; END; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

An UPD ATE ROW t rig ger can specify t h e colu mn s being up dat ed as a cond it ion f or fir ing t he By Kevin Owens t r igger . The sy nt ax is: Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

OF column_name [,column_name] Pages: 44 8

For exam ple, t h e follow ing t r igger f ir es only w h en colum ns M or P are in clu ded in t he UPDATE st at ement . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CREATE OR REPLACE TRIGGER temp_aur dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he AFTER INSERT OR UPDATE OF M, P ON TEMP bu sin ess evolv es. Topics cov er ed include: FOR EACH ROW BEGIN dbms_output.put_line View in g const r aint s in t h e dat a dict ion ar y ('after insert or update of m, p'); END; Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res

DECLARE Dat a t y pes and

comp osit e st r u ct u re

or han and except ions As w itEr h rany PL/dling SQL block, t his is not necessar y if t here are no local d eclar at ions. I nt er - pr ocess com mu nicat ions

WHEN (BOOLEAN EXPRESSION) Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign

k ey, ch eck , and m uch m or e This clause is opt ion al and can be u sed t o f ilt er t he condit ion f or w hen y ou w ant t o f ire t he Pr ogr am t r igger . m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int Why ellig wou en tld, com y ou plex use tdat h is? abases. The WHEN opt ion can b e used on an y ROW lev el t r igger . Con sid er up dat ing a t able w it h man y r ow s. A r ow level t r igg er can im pact p er f orm ance. I f a m illion Team ] at ed, one million ex ecu t ions of t h e t r ig ger w ill be n ot iced. The per for m ance r[ ow s ar eLiB upd im pact f r om t he r ow t rig ger could b e r eason enoug h t o r em ov e it f r om t he applicat ion. How ev er , t her e m ay be special circum st ances in wh ich t h e t r ig ger is needed. Th e WHEN

clause ov id [ Team prLiB ] es an op por t un it y t o cont r ol t he t r igger ex ecut ion —t o h ave it f ir e on shor t t r ansact ions and n ot on m assiv e up dat es. Wit hin t he par en t heses of t he WHEN clau se, t h e r ef erence t o colu mn v alues is w it h t he follow ing syn t ax :

NEW.COLUMN_NAME This is t he syn t ax for ref er encing a colum n in t h e WHEN clau se of an I NSERT or UPDATE t rig ger. OLD.COLUMN_NAME This can be u sed in t he WHEN clau se of UPDATE an d D ELETE ROW t r igger s. This does n ot ev alu at e in I NSERT ROW t rig gers. To illust r at e, t he follow in g is an AFTER I NSERT r ow t r igger t h at f ires on ly wh en t h e colu m n v alue for N is equal t o 0 . •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE OR REPLACE TRIGGER temp_air AFTER INSERT ON Hall TEMP Pub lish er: Prent ice PTR FORPub EACH Dat e:ROW Decem ber 0 5, 2 003 WHEN (NEW.N = 0) I SBN: 0- 13 -0 850 33 -0 BEGIN Pages: 44 8 dbms_output.put_line('executing temp_air'); END;

Ef fect e an dt r man abases w it h st Oratacle! Sy: st ems and dat ab ase ex per t The afively or emcreat ent ioned iggerage w illcom f ir eplex w it hdat t his n ex t SQL em ent Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor at e bu siness INSERT INTO TEMPporVALUES (0); r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: The af or em ent ioned t r igger w ill not f ir e w it h t he follow in g t w o st at ement s: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res INSERT INTO TEMP VALUES (2); Dat a t y pes and comp osit e st r u ct u re INSERT INTO TEMP VALUES (NULL); Er r or han dling and except ions The v Ialue n is eit her nt er -ofprNEW. ocesscolum com mu nicat ionst he value in clu ded in t h e SQL st at em ent , NULL, or t h e v alue fr om t he colum n DEFAULT. Con sid er t he TEMP TABLE: Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly CREATE tempdat (Nabases. NUMBER DEFAULT 0, M NUMBER); int ellig enTABLE t , com plex [ Team LiB ] The af or em ent ioned t r igger w ill f ir e f or t h e follow ing SQL st at em ent . This is because NEW. N is equal t o t h e DEFAULT, w h ich is 0. The t r igger f ires on ly wh en NEW .N is zero.

[ Team LiB ] INSERT INTO TEMP (M) VALUES (3);

You can code OLD. colum n in an I NSERT t r igger . I t is n ot a sy nt ax er r or and ev alu at es t o NULL. The follow ing illust rat es a t r igger w it h a t r igg er ing event of I NSERT OR UPD ATE. The WHEN clau se st ip ulat es t hat t he t r igg er fir es on eit her of t h e follow ing condit ons:

OLD.N=0 AND NEW.N=1

This ex pr ession does not ev aluat e on an y I NSERT st at em ent s b ecause OLD. N is NULL. I t m ay be TRUE or FALSE on UPD ATE st at em ent s.

OR • NEW.N=1

ev aluat es on I NSERT an d UPDATE st at em en t s. Table ofThis Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE REPLACE TRIGGER temp_biur Pub lishOR er: Prent ice Hall PTR BEFORE INSERT OR UPDATE ON TEMP Pub Dat e: Decem ber 0 5, 2 003 FOR EACH ROW I SBN: 0- 13 -0 850 33 -0 WHEN (OLD.N = 0 AND NEW.N=1 OR NEW.N=1) Pages: 44 8 BEGIN dbms_output.put_line('executing temp_biur'); END; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin ens plor es PL/ SQL, Oron acle's answ er o t hNe isSt1r uct ed UPDATEs Query Langu aget h( eSQL) The af Ow or em entex ioned t r igger f ires I NSERTs w ht en an ur d on wh en v alu, eanofd t eaches youfr om w hat0 yt oou1.n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. N chan ges Using t o- follow r uct d ex amex ples, t his book s t echniq uesf unct t o t ake The W easyHEN clause caninst in clu deions anyan Boolean pr ession . I t mpr ayesent include PL/ SQL ion calls. adv ant ag einofg Or acle such gers and ored pr ocedThis ur es-t rig f eat u r es t hat allow y our The f ollow illust r atfeat es tur heesuse of as t het rig SQL f unct ionst BETWEEN. ger fir es only w hen t o value incor por at ewbu siness tdat he ab in ases ser t ed is bet een 1 andr ules 10. w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enfTRIGGER orcem en ttemp_aur CREATE OR REPLACE AFTER UPDATE ON TEMP PL/ SQL p r ogr am un it s and langu age f eat u res FOR EACH ROW WHEN (NEW.N BETWEEN 1 AND 10) Dat a t y pes and comp osit e st r u ct u re BEGIN dbms_output.put_line('executing temp_aur'); Er r or han dling and except ions END; I nt er - pr ocess com mu nicat ions The WDeclar HEN clause is f orr aint ROW r igger s only . ar y k ey , u nique, f or eign k ey, ch eck , and m uch at iv e const s, tincluding p rim m or e [PrTeam ] Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce ogr amLiB m ing for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

6.4 Trigger Body The t rig ger body is wr it t en in PL/ SQL. There are PL/ SQL exp ression s t hat only h ave m eaning w it hin a t r igg er body . These t opics ar e cov er ed in t h e follow ing par agr aph s. A t rigg er body can r ef er t o t wo st at es of a colum n valu e. The syn t ax for each st at e is:

•:NEW.COLUMN_NAME Table of Content s :OLD.COLUMN_NAME Pr ogr am m ing Or a cl e ® Tr i gger s and

Stor e d P roce dure s, Thir d Edi ti on

By Kevin Owens

: NEW. COLUMN_NAME is t h e sy nt ax for r efer en cin g a colu m n v alue w it h in t h e body of t he r ow I NSERT and UPD ATE t rigg er s. Th is ex pr ession ev aluat es t o NULL in D ELETE r ow t rigg er s. I t Pub lish er: Prent ice Hall PTR evalu at es t o t h e valu e inclu ded in t h e SQL I NSERT or UPD ATE st at em ent . Pub Dat e: Decem ber 0 5, 2 003

I SBN:st0-at 13em -0 850 I f t he SQL en33 t d-0oes not refer ence a colum n, t he f ollow ing r ules app ly : Pages: 44 8

For I NSERT st at em ent s, : NEW.COLUMN_NAME is eit her NULL or t h e valu e of t he DEFAULT used in creat ing t he t able. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t For UPDATE st at em ent s, : NEW .COLUMN_NAME is t h e valu e cu r rent ly in t h e t able. Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t: eaches you w hat y ou is n eed t o for kn ow t o build ust an dr ow comt rplex ablyases f orevyaluat our bes usiness. OLD. COLUMN_ NAME valid UPDATE androb DELETE igg erdat s on . Th is to NULL for I NSERT t r igg er s. The : OLD. COLUMN_NAME evaluat es t o t h e valu e cu rr ent ly in t he Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake t able. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ases t of o incor por at e bu siness hich ar e easy t o man age and m odif t heical for Theab v alues : OLD. COLUMN_ NAMEr ules and w : NEW. COLUMN_NAME exp ression s arye as ident bu sin ess evolv es. Topics cov er ed include: BEFORE an d AFTER r ow t r igg er s. The ch oice of a BEFORE or AFTER r ow t r igger is a choice t o execut e t h e t r igger b ef ore or aft er Oracle const r aint en for cem ent . Visibilit y t o : OLD and NEW v alues is ident ical wr aint it h each. eat ion is tar hat View in g const s in t hOne e datcav a dict y y ou can chang e t he v alue of : NEW. COLUMN_NAME in BEFORE r ow t r igger s, not in AFTER r ow t r igg er s. Com plex r ule enf orcem en t The f ollow in g illust r at es a t able t hat has BEFORE UPD ATE an d AFTER UPDATE row t r igger s. I t pr int sPL/ t he oldpand colum n vlangu alu es.age f eat u res SQL r ograft amerun it s and Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions CREATE TABLE TEMP(N NUMBER, M NUMBER DEFAULT 5); I nt er - pr ocess com mu nicat ions CREATE OR REPLACE TRIGGER temp_bur Declar at iv e ON const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch BEFORE UPDATE TEMP m or e ROW FOR EACH BEGIN Pr ogrdbms_output.put_line('BUR am m ing Oracle Tr igger s and St old or ed N:'||:old.n|| Pr oced ur es , Th ir ' d Ed it ion , is an inv aluable r esou rce M:'||:old.M); for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly dbms_output.put_line('BUR new N:'||:new.n|| ' M:'||:new.M); int ellig en t , com plex dat abases. END; [CREATE Team LiB OR ]REPLACE TRIGGER temp_aur AFTER UPDATE ON TEMP FOR EACH ROW BEGIN

dbms_output.put_line('AUR old N:'||:old.n|| ' M:'||:old.M); [ Team LiB ] dbms_output.put_line('AUR new N:'||:new.n|| ' M:'||:new.M); END;

The OLD and NEW valu es ar e t he sam e for BEFORE and AFTER row t r ig gers.

SQL> INSERT INTO TEMP (n) VALUES (1); SQL> UPDATE TEMP SET n=n+1 WHERE n>=1; BUR old: N=1 M=5 BUR new: N=2 M=5 AUR old: N=1 M=5 •AUR new: N=2 Table of Content s M=5 Pr ogr am m ing Or a cl e ® TrSET i ggerm=2 s and WHERE Stor e d PM=5; roce dure s, SQL> UPDATE TEMP BUR old: N=2 M=5 By Kevin Owens BUR new: N=2 M=2 AUR old: N=2 M=5 AURPub new: lish er:N=2 Prent ice M=2 Hall PTR

Thir d Edi ti on

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

The BEFORE UPD ATE r ow t rig ger is changed. I t incr em ent s t he : NEW .N. This eff ect iv ely Pages: 44 8 chang es t he v alue insert ed int o t he d at abase. This t r igg er has one lin e added, t he st at em en t t o in cr em en t : NEW. N. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. CREATE OR REPLACE TRIGGER temp_bur Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake BEFORE UPDATE ON TEMP adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our FOR EACH ROW dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he BEGIN bu sin:NEW.N ess evolv es. Topics cov er ed include: := :NEW.N + 1; dbms_output.put_line('BUR old N:'||:old.n|| ' M:'||:old.M); dbms_output.put_line('BUR new N:'||:new.n|| ' M:'||:new.M); View in g const r aint s in t h e dat a dict ion ar y END; Com plex r ule enf orcem en t The r esult s ofptrhogr e sam UPDATE em ent s sh ow t hat N w as in ser t ed in t o t h e PL/ SQL am eunI NSERT it s and and langu age f eatst u at res dat ab ase w it h an incr em ent ed valu e. The f ir st UPDATE in t he f ollow in g st at em en t in cr ement s: N t o NDat + a1,t yf pes r om and 1 t ocomp 2 . The inucrem ositt reigg st er r u ct re en t s N ag ain t o a value of 3 . The second UPD ATE st at ement does n ot r efer en ce t he colum n N, yet it is incr em ent ed in t he colum n. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch SQL> mINSERT or e INTO TEMP (n) VALUES (1); SQL> UPDATE TEMP SET n=n+1 WHERE n>=1; Pr ogrold: am m ing BUR N=1Oracle M=5 Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for abase d evM=5 elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly BURdat new: N=3 int ellig en t , N=1 com plex AUR old: M=5 dat abases. AUR new: N=3 M=5 [SQL> TeamUPDATE LiB ] TEMP SET m=2 WHERE M=5; BUR old: N=3 M=5 BUR new: N=4 M=2 AUR old: N=3 M=5

AUR new: M=2 [ Team LiBN=4 ] [ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

6.5 Example Row Triggers Con sider t he follow ing t able:

CREATE TABLE TEMP(X NUMBER, Y NUMBER, Z NUMBER DEFAULT 5);



Table of Content s

. am Wrmiting e aOrt rig es ONLY erdure t hes,f Thir ollow ingti on cond it ion s: Pr1 ogr a cl eger ® Trtihat ggerfir s and Stor e d und P roce d Edi By Kevin Owens

UPDATE wh en Y ch anges f r om NULL t o a NOT NULL v alue. Pub lish er:I NSERT Prent ice Hall PTR X w hen

is bet w een 1 and 10 .

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

CREATE OR REPLACE TRIGGER temp_aiur Ef fect ively AFTER creat e an d manOR ageUPDATE com plexOFdatYabases w it h Or acle! Sy st ems and dat ab ase ex per t INSERT ON TEMP Kevin Ow ens plor esROW PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d FORexEACH t eaches you w hat(OLD.Y y ou n eed o kn owand t o build ustNOT an dNULL com plex dat ab ases f or y our b usiness. WHEN IS t NULL NEW.Yrob IS OR NEW.X BETWEEN 1 AND 10) Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake BEGIN adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CASE dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he WHEN inserting THEN bu sin ess evolv es. Topics cov er ed include: dbms_output.put_line('X := '||:new.x); WHEN updating THEN View in g const rdbms_output.put_line aint s in t h e dat a dict ion ar y ('Y is reset from NULL'); END CASE; Com plex r ule enf orcem en t END; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re 2 . Wr it e a t rig ger t o p rin t t h e cur rent v alu es in a r ow being delet ed . Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e CREATE OR REPLACE TRIGGER temp_adr Pr ogr am m ing Oracle Tr igger AFTER DELETE ONs and TEMPSt or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, FOR EACH ROW d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , BEGIN com plex dat abases. dbms_output.put_line [ Team LiB ] (:old.x||' '||:old.y||' '||:old.z); END;

3 . WrLiB it e all [ Team ] six possib le r ow lev el t r igger s: BEFORE an d AFTER ROW f or I NSERT, UPD ATE, and DELETE.

Tri gge r Ty pe BEFORE I NSERT



Tri gge r Te m p la t e Cod e

CREATE OR REPLACE TRIGGER temp_bir BEFORE INSERT ON TEMP FOR EACH ROW BEGIN dbms_output.put_line('executing temp_bir'); END;

AFTERTable of Content s

Pr ogr am m ing Or a cl e ® TrCREATE i gger s and ORStor REPLACE e d P roce dure TRIGGER s, Thir d temp_air Edi ti on I NSERT

AFTER INSERT ON TEMP FOR EACH ROW BEGIN Prent ice Hall PTR dbms_output.put_line('executing temp_air'); END; Decem ber 0 5, 2 003

By Kevin Owens

Pub lish er: Pub Dat e:

I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 BEFORE UPDATE ( see CREATE OR REPLACE TRIGGER temp_bur BEFORE UPDATE ON TEMP not e) FOR EACH ROW Ef fect ively creat e an dBEGIN man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t dbms_output.put_line('executing Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r ucttemp_bur'); ur ed Query Langu age ( SQL) , an d END; t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake AFTER adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our UPDATE ( see CREATE OR REPLACE TRIGGER temp_aur dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he AFTER UPDATE ON TEMP not e) bu sin ess evolv es. Topics cov er ed include: FOR EACH ROW BEGIN dbms_output.put_line('executing temp_aur'); View in g const r aint s in t h e dat a dict ion ar y END; Com plex r ule enf orcem en t BEFORE PL/ SQL p r ogr am un it s and langu age f eat u res CREATE OR REPLACE TRIGGER temp_bdr DELETE Dat a t y pes and BEFORE comp ositDELETE e st r u ctON u re TEMP FOR EACH ROW BEGIN Er r or han dling and except ions dbms_output.put_line('executing temp_bdr'); I nt er - pr ocess com END; mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch mAFTER or e CREATE OR REPLACE TRIGGER temp_adr DELETE ONedTEMP Pr ogr am m ing Oracle AFTER Tr iggerDELETE s and St or Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce FOR d EACH for dat abase d ev elopers, esignROW er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly BEGIN int ellig en t , com plex dat abases. dbms_output.put_line('executing temp_adr'); [ Team LiB ] END;

e. ]The OF COLUMN_NAME clause is op t ional on UPDATE row and UPD ATE [ TeamNot LiB st at ement level t r igg er s ( st at em en t lev el t rig gers are cov ered in Ch apt er 7) . The WHEN (Boolean expression) is opt ional w it h all ROW t r igg er s. 4 . Wr it e t w o t rig gers t hat accom plish t h e same as t he p rior six t r igg er s.

CREATE OR REPLACE TRIGGER temp_biudr BEFORE INSERT OR UPDATE OR DELETE ON TEMP FOR EACH ROW BEGIN CASE • Table of Content s WHEN Pr ogr am m ing Or a cl e ® Tr iinserting gger s and StorTHEN e d P roce dure s, Thir d Edi ti on dbms_output.put_line('inserting before'); By Kevin Owens WHEN updating THEN dbms_output.put_line('updating before'); WHEN deleting THEN Pub lish er: Prent ice Hall PTR dbms_output.put_line('deleting before'); Pub Dat e: Decem ber 0 5, 2 003 END CASE; I SBN:END; 0- 13 -0 850 33 -0 Pages: 44 8

CREATE OR REPLACE TRIGGER temp_aiudr AFTER INSERT OR UPDATE OR DELETE ON TEMP FOR EACH ROW Ef fect ively BEGIN creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens exCASE plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d WHEN THEN t eaches you w hat y ouinserting n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. dbms_output.put_line('inserting after'); Using easy- t o- follow r uct ionsTHEN an d ex am ples, t his book pr esent s t echniq ues t o t ake WHEN inst updating after'); adv ant ag e of Or acle dbms_output.put_line('updating feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor pordeleting at e bu siness r ules w hich ar e easy t o man age and m odif y as t he WHEN THEN dbms_output.put_line('deleting after'); bu sin ess evolv es. Topics cov er ed include: END CASE; END; View in g const r aint s in t h e dat a dict ion ar y Com plex [ Team LiB ] r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

6.6 A Table with Oracle Constraints and Business Rules I n t his sect ion a set of b usiness r u les is ap plied t o I NSERTS on t h e PROFESSORS t ab le. W e w ill init ially en for ce t he r ules w it h a BEFORE I NSERT r ow t rigg er . This t r igger w ill per for m a v ariet y of t ask s. I t w ill: Ov err ide colum n v alu es upon insert . •

En for ceTable a st rofictContent bu sinsess r ule t h at m ay p ot en t ially r esult in t he t ran sact ion being

r ejmect t hr a call t o Stor RAIeSE_APPLI ON_ ERROR. Pr ogr am inged Or a cl eoug ® Trhi gger s and d P roce dureCATI s, Thir d Edi ti on By Kevin Owens

Tak e an act ion . I n t his case pr in t u sin g D BMS_OUTPUT.

Pub lish er: Prent ice Hall PTR

6.6.1 The Environment Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

The locat ion44of Pages: 8 t his logic is illust r at ed in Figur e 6- 2 . Th e gr ay ed ar ea indicat es w her e t his t r igger code f it s int o t he ov er all I NSERT st at em ent pr ocess.

Figu r e 6 - 2 . Loca t ion of Tr i gge r Cod e. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re The b usiness ru les in t his ex am ple ar e being app lied t o t h e PROFESSORS t ab le. Her e is a descr ipt of t dling h at t ab le: except ions Er rion or han and I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e SQL> desc professors PrName ogr am m ing Oracle Tr igger s and St or ed Pr oced urType es , Th ir d Ed it ion , is an inv aluable r esou rce Null? for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly -----------------------------------------------int ellig en t , com plex dat abases. PROF_NAME NOT NULL VARCHAR2(10) SPECIALTY NOT NULL VARCHAR2(20) [ HIRE_DATE Team LiB ] NOT NULL DATE SALARY NOT NULL NUMBER(7,2) TENURE NOT NULL VARCHAR2(3) DEPARTMENT NOT NULL VARCHAR2(10)

[ Team LiB ] and t h e CHECK const r ain t s f or t his t ab le are: The n am e of t he d ep art ment is r est r ict ed t o a lim it ed set .

ALTER TABLE professors ADD CONSTRAINT ck_professors_department CHECK (department IN ('MATH','HIST','ENGL','SCIE'));



The t en ur e field is YES or NO. Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

ALTER TABLE professors ck_professors_tenure Pub Dat e:CHECK Decem ber 0 5, 2 003 IN ('YES','NO')); (tenure

Pub lish er:ADD PrentCONSTRAINT ice Hall PTR I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

The salar y has an u pper lim it of 30 ,0 00. 0 0.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ALTER TABLE professors t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ADD CONSTRAINT ck_professors_salary CHECK (salary < 30000); Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

6.6.2 The Procedural Constraints to Enforce View in g const r aint s in t h e dat a dict ion ar y The f ollow in g list s t h e r ules we are ask ed t o enf orce. Ru les ar e g rou ped u sin g on e t he cat egor iesplex f r omr ule in Figur e 6- 1enan Com enf orcem t d 6- 2 . PL/ SQL p r ogr am un it s and langu age f eat u res

OVERRIDE COLUMN RULES Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions Tr uncat e t he HI RE_DATE t o en su re t hat all inser t ed dat es hav e a zer o for h our s, m in ut es, and second s. I nt er - pr ocess com mu nicat ions Con ver t t h e DEPARTM ENT t o up percase. This is j ust t o ensur e t h at an I NSERT of ' Mat h ' Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch is con ver t ed t o ' MATH.' m or e Rou nd all n ew salar ies t o t he n ear est dollar . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases.

REJECT THE TRANSACTION RULE [ Team LiB ]

Reject an y I NSERT w h er e t h e salar y of t he p r ofessor ex ceeds a $10 , 000 lim it and t h e depar t m ent is ' ENGL.' Not e: All ot h er salar ies ar e const r ained t o t he CHECK const r ain t

t hat [ Team LiBhas ] a lim it of $3 0, 000 .

TAKE ACTION RULE Wr it e a m essage u sing DBM S_OUTPUT. The t rig ger cod e fir st conv er t s t he : NEW v alues. This includ es t ru ncat ing t he HI RE_DATE colum n. Follow in g t hat , it ch eck s f or Eng lish depar t m ent salar y r est r ict ion. Th is can pot ent ially r eject t h e inser t . Finally , t he t rig ger t ak es t he act ion t o p rint .



Table of Content s

CREATE OR REPLACE TRIGGER professors_bir Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on BEFORE INSERT ON professors By Kevin Owens FOR EACH ROW DECLARE msg VARCHAR2(100) := Pub lish er: Prent ice Hall PTR 'The salary exceeds the ENGL maximum of $10,000.00'; Pub Dat e: Decem ber 0 5, 2 003 BEGIN 0- 13 -0 850 33 -0 --I SBN: --------------------------------------Pages: OVERRIDE 44 8 COLUMN RULES -- --------------------------------------- truncate hours, minutes, seconds of hire date := TRUNC(:NEW.hire_date); Ef fect:NEW.hire_date ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d -- you round salary t eaches w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. :NEW.salary := ROUND(:NEW.salary); Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake --agconvert department to as upper caseand st ored pr oced ur es- f eat u r es t hat allow y our adv ant e of Or acle feat ur es such t rig gers dat ab:NEW.department ases t o incor por at e:= buUPPER(:NEW.department); siness r ules w hich ar e easy t o man age and m odif y as t he bu sin-ess-------------------------------------evolv es. Topics cov er ed include: -- REJECT TRANSACTION RULES -- -------------------------------------View in g const r aint s in t h e dat aAND dict ion ar y IF :NEW.department='ENGL' :NEW.salary > 10000 THEN RAISE_APPLICATION_ERROR(-20000,msg); Com IF; plex r ule enf orcem en t END PL/ -------------------------------------SQL p r ogr am un it s and langu age f eat u res --- TAKE ACTION RULES Dat a t y pes and comp osit e st r u ct u re -- -------------------------------------dbms_output.put_line Er r or han dling and except ions ('Before Insert Row Trigger Action'); END; I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e

6.6.3 Before versus After

Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Thedat af or em ent ioned t r igger enf orces sev er bu siness Allg ar foran cedd m pr aint ior tain o Ort racle' for abase d ev elopers, d esign er s, and pral oj ect leaderrsules. look in t oeben uild uly s const r ain orplex cem ent Th e " Ov er r ide Colu mn " t r igg er cod e m ust b e in a Befor e- I n ser t Row int ellig en t , enf com dat.abases. t r igger , bu t t h e " Reject t he Tr ansact ion" an d " Take Act ion" logic shou ld be aft er t h e Or acle [ Team const r ain LiB t . I] n gener al, you only w an t t o pr ocess d at a f or an applicat ion b usiness ru le t hat you k now is g ood—dat a t h at has passed int egr it y check s. This sh if t s t h e locat ion of t h e cod e t o t he archit ect ur e dr aw n in Figur e 6- 3 .

Figu r e 6 - 3 . I m pr ov ed Loca t i on of Tr igge r Code .

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

To im plem en t t h is chang e w e need t o creat e t w o t r ig ger s and split t h e PL/ SQL logic b et ween fect ively creat an d manIage comt plex datper abases h "Or acle! st ems n" and dation. ab ase tEf he t rig gers. Th ee BEFORENSERT rig ger for m swt it he Over r idSy e Colum fu nct Thex e per t Kevin Owgens exer plor esePL/ SQL, answ er t o row t h e St r uct ur ed ageer( SQL) , an d r em ainin t r igg cod goes in Or anacle's AFTERI NSERT t r ig ger. TheQuery f ollowLangu ing t r igg is t he tBEFOREeaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. I NSERT row t r ig ger , w it h com m en t s r emov ed. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: CREATE OR REPLACE TRIGGER professors_bir BEFORE INSERT ON professors View inROW g const r aint s in t h e dat a dict ion ar y FOR EACH BEGIN Com plex r ule enf orcem en t :NEW.hire_date := TRUNC(:NEW.hire_date); :NEW.salary := un ROUND(:NEW.salary); PL/ SQL p r ogr am it s and langu age f eat u res :NEW.department := UPPER(:NEW.department); END; Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions The AFTER- I NSERT t rig ger, wh ich r un s aft er Oracle's const r aint en for cem ent , w ill p er f orm t he " Reject he- pr Trocess ansactcom ion"mu t ask ( ch eck f or an inv alid salary con dit ion) and perf or m t he " Tak e I ntter nicat ions Act ion" t ask , w h ich is t o pr in t a m essage. The follow in g is t he AFTER- I NSERT t r igg er , Declar at ivov e const com ment s rem ed . r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. CREATE OR REPLACE TRIGGER professors_air [ Team INSERT LiB ] AFTER ON professors FOR EACH ROW DECLARE msg VARCHAR2(100) :=

'The salary exceeds the ENGL maximum of'|| $10,000.00'; [ Team LiB ] BEGIN IF :NEW.department='ENGL' AND :NEW.salary > 10000 THEN RAISE_APPLICATION_ERROR(-20000,msg); END IF; dbms_output.put_line ('Before Insert Row Trigger Action'); END;

6.6.4 Using Packages for Procedural Constraints Ru les f or a t rig ger can p ile u p. A t r igger can quick ly becom e com plex. Because an inv alid t r igger can int er fere wit h t h e oper at ions of an applicat ion, log ic sh ould be m ov ed f rom t he t r igger t o PL/ SQL p ack ages. I f a p iece of code is n ot per for m ing as exp ect ed, t hat pr ocedu re • Table of Content s call can b e r em ov ed f r om t he t rigg er . A t r igger can and should be ab le t o enf orce m any Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on bu sin ess r ules, but each r ule shou ld b e aut onom ou s. By Kevin Owens

Each check const r aint can b e enabled an d disab led w it h an ALTER TABLE st at ement . You should be ab le t o accom plish t h e sam e lev el of gr anular it y w it h t r ig gers. Pub lish er: Prent ice Hall PTR

The Pub f ollow g illust encapsulat ing t he business ru le logic in a pack age. This p ack age is Dat e:inDecem berr at 0 5,es 2 003 called PROFESSORS_CONS because it enf or ces const r aint s on t h e PROFESSORS t ab le. Th e I SBN: 0- 13 -0 850 33 -0 pack age specif icat ion is list ed f irst and t hen t he t r igg er s. Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin OwOR ensREPLACE ex plor esPACKAGE PL/ SQL, Or acle's answ er t o tIS h e St r uct ur ed Query Langu age ( SQL) , an d CREATE professors_cons t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. FUNCTION salary(sal professors.salary%TYPE) Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake RETURN professors.salary%TYPE; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat abFUNCTION ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he hire_date(hd professors.hire_date%TYPE) bu sin ess evolv es. Topics cov er ed include: RETURN professors.hire_date%TYPE; FUNCTION department(dept professors.department%TYPE) View in g const r aint s in t h e dat a dict ion ar y RETURN professors.department%TYPE; Com plex r ule enf orcem en t PROCEDURE validate_salary (dept professors.department%TYPE, PL/ SQL p r ogr am un it s and langu age f eat u res sal professors.salary%TYPE); Dat a t y pes and comp osit e st r u ct u re PROCEDURE print_action; Er r or han dling and except ions END professors_cons; I nt er - pr ocess com mu nicat ions Declar iv ly e const p rim k ey f orage. eignThe k ey,BEFOREch eck , and m uch The t rig gersaton m aker aint callss, t including o in div id ual f unarctyion s ,inu nique, t he pack I NSERT m or e t h e logic in t he p ack age r at h er t han per for m each ind ividu al t r un cat e and rou nd. t r igger u ses Gr ant ed t his is n ot m uch logic t o en capsulat e. ROUND, UPPER, and TRUNC are n ot ex t ensiv e Pr m ingmOracle igger s and or ed Pr oced es , Th Ed could it ion , is an invealuable r esou rce datogr a tam r ansfor at ions.TrHow ever , a St mor e r ealist ic ur b usin essir rdule st ipulat t hat t he for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly HI RE_ DATE on an inser t be ch anged t o t h e nex t b usin ess d ay. Such a t r ansfor m at ion cou ld int ellig en t , com plex dat abases. include dat abase look ups t o det er min e t he n ex t w ork ing day . [The Team LiB ] I NSERT r ow t r igg er w it h calls t o t h e const r ain t s pack age is show n her e. BEFORE-

[ Team LiB ] CREATE OR REPLACE TRIGGER professors_bir BEFORE INSERT ON professors FOR EACH ROW BEGIN :NEW.hire_date := professors_cons.hire_date(:NEW.hire_date); :NEW.salary := professors_cons.salary(:NEW.salary); :NEW.department := professors_cons.department(:NEW.department); END;

The AFTER- I NSERT t rig ger is t w o p rocedur e calls. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE OR REPLACE TRIGGER professors_air Pub lish er: Prent ice PTR AFTER INSERT ON Hall professors Pub Dat e: Decem ber 0 5, 2 003 FOR EACH ROW I SBN: 013 -0 850 33 -0 BEGIN professors_cons.validate_salary Pages: 44 8 (:NEW.department, :NEW.salary); professors_cons.print_action; END; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d The p ackag hatn im plem enow ts th business r ules t he plex f ollowdat ingab . ases f or y our b usiness. t eaches youewbody hat ytou eed t o kn t oe build rob ust an dis com Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: CREATE OR REPLACE PACKAGE BODY professors_cons IS FUNCTION salary(sal View in g const r aint s in t hprofessors.salary%TYPE) e dat a dict ion ar y RETURN professors.salary%TYPE IS BEGIN Com plex r ule enf orcem en t RETURN ROUND(sal); PL/ SQL p r ogr am un it s and langu age f eat u res END salary; Dat a t y peshire_date(hd and comp osit e professors.hire_date%TYPE) st r u ct u re FUNCTION RETURN professors.hire_date%TYPE IS Er r or han dling and except ions BEGIN RETURN TRUNC(hd); I nt er - pr ocess com mu nicat ions END hire_date; Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch FUNCTION department(dept professors.department%TYPE) m or e RETURN professors.department%TYPE IS Pr ogrBEGIN am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce RETURN UPPER(dept); for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly END department; int ellig en t , com plex dat abases. PROCEDURE validate_salary [ Team LiB ] (dept professors.department%TYPE, sal professors.salary%TYPE) IS

msg [ Team LiB ] VARCHAR2(100) := 'The salary exceeds the ENGL maximum of $10,000.00'; BEGIN IF dept ='ENGL' AND sal > 10000 THEN RAISE_APPLICATION_ERROR(-20000,msg); END IF; END validate_salary; PROCEDURE print_action IS BEGIN dbms_output.put_line ('Before Insert Row Trigger Action'); END print_action; END professors_cons; •

Table of Content s

6.6.5 Managing Error Codes and Messages

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Lar ge sy st ems ( e. g. , op er at in g sy st em s an d d at abase pr odu ct s) do not em bed err or code nu mb er s an d messag es as lit er al v alues w it hin t he cod e. The follow ing pr oced ur e, t ak en f rom lish er: Prent ice Hall PTR t enf orcem en t p ack age in Sect ion 6. 5 , is an exam p le of a bu ried t he Pub pr ofessor ' s con st rain Pubcode Dat e: num Decem ber an 0 5,d2 m 003essag e t ext . err or ber I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

PROCEDURE validate_salary Ef fect ively(dept creat eprofessors.department%TYPE, an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex professors.salary%TYPE) plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d sal t eaches IS you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. msg VARCHAR2(100) := Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 'The salary exceeds the ENGL maximum of'|| '$10,000.00'; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our BEGIN dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he IF dept ='ENGL' AND sal > 10000 THEN bu sin ess evolv es. Topics cov er ed include: RAISE_APPLICATION_ERROR(-20000,msg); END IF; END Viewvalidate_salary; in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t As new cod e is developed, t he m anag em ent of er r or codes is im por t ant . An ap plicat ion dev elop n eeds t oam k now n exlangu t av ailable mu essage num ber . This can easily be det er m ined PL/er SQL p r ogr un itt sheand age f eat res w hen er r or code n um ber s are cent r alized. Th e follow ing packag e is an ex am ple of encapsulat errand or mcomp essagosit es.e st r u ct u re Dat a ing t y pes The f ollow g erdling r ors and packag e encapsulat es t he er r or num b er s an d m essag e t ext for all t he Er r or inhan except ions err or s of an app licat ion. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e PrCREATE ogr am mOR ing REPLACE Oracle Tr PACKAGE igger s anderrors St or ed IS Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect s look in g t o b uild an d m aint ain t r uly eng_dept_sal CONSTANT PLS_INTEGER := leader -20001; int ellig en t , com plex dat abases. PLS_INTEGER := -20002; app_error_02 CONSTANT app_error_03 CONSTANT PLS_INTEGER := -20003; [ Team LiB ] eng_dept_sal_txt CONSTANT VARCHAR2(100) := 'The salary exceeds the ENGL maximum of'|| '$10,000.00';

app_error_02_txt CONSTANT VARCHAR2(100) := 'vacant'; [ Team LiB ] app_error_03_txt CONSTANT VARCHAR2(100) := 'vacant'; END errors;

This chan ges t he pr ocedu re in t h e const rain t s enfor cement pack age f or t he p r ofessor 's t able t o t he f ollow ing :

PROCEDURE validate_salary (dept professors.department%TYPE, sal professors.salary%TYPE) IS • BEGIN Table of Content s Pr ogr am m ing a cl e ® ='ENGL' Tr i gger s and Storsal e d P roce s, Thir d Edi ti on IFOrdept AND > dure 10000 THEN By Kevin Owens RAISE_APPLICATION_ERROR (errors.eng_dept_sal, errors.eng_dept_sal_txt); Pub lish er: END Prent IF; ice Hall PTR END validate_salary; Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

6.6.6 Trigger Architecture We st ar t ed w it h a set of business ru les t hat wer e enfor ced w it h in a sin gle r ow t r igger . Ef fect ively e an d man abases Or acle! ISy st emsan and dat ab ase ex per t Log ically , itcreat m ade sense t o age splitcom t h eplex logicdat bet w een twhitehBEFORENSERT d AFTERI NSERT Kevin ens specific ex plor eslogic PL/ SQL, Or acle's answenercap t o su t hlat e St Query ageor( SQL) , an d t r iggerOw s. The of each r u le was edr uct int ouraedp ack age.Langu Th e err d ef init ions tweaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ere f ur t her encapsulat ed int o an er r ors packag e. The f in al ar chit ect u re is sh ow n in Figur e 64. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Figu r er ules 6 - 4w. hich Fi na ch tito ect e .and m odif y as t he dat ab ases t o incor por at e bu siness arleAr easy manur age bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions The ERRORS Declar atpivack e const age has r aintno s, including body . I t isp arim cent ar yr al k ey r eposit , u nique, ory for f or eign constkan ey,t sch t hat eck can , andb em uch r ef erenced m or e by v ariou s par t s of t h e business r ule enfor cement app licat ion code. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce [ Team LiB ] d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly for dat abase int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Chapter Seven. Statement Level Triggers 7. 1 SEQUENCE OF EVENTS 7. 2 I NSERT STATEMENT TRI GGER SYNTAX 7. 3 STATEMENT LEVEL AGGREGATI ON •

7. 4 PROCESSI ROW Table of NG Content s CAPTURED DATA

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

This chap t er begins w it h t h e sam e t r igg er t hat st art ed Ch apt er 6, ex cept t his is a st at ement By Kevin Owens level t r igg er . We st ar t w it h a TEMP t able. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

DROP TABLE Pages: 44TEMP; 8 CREATE TABLE temp (N NUMBER);

Now cr eat e an ALTER- I NSERT- STATEMENT t r igger . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CREATE OR REPLACE TRIGGER temp_ais dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he AFTER INSERT ON TEMP bu sin ess evolv es. Topics cov er ed include: BEGIN dbms_output.put_line('executing temp_ais'); END; View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t The f ollow in g in ser t s hav e d if fer ent r esult s t h an t h e beginn ing of Ch apt er 6, w hich dem onst r at edp raogr ROW r igger . Welangu b eg in b yf eat inser t ing a sing le r ow. PL/ SQL am tun it s and age u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions nt er -feedback pr ocess com mu nicat ions SQL> I set off SQL> INSERT INTO temp VALUES (1); -- insert 1 row Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch executing temp_ais or e SQL> mINSERT INTO temp VALUES (1); -- insert 1 row executing temp_ais Pr ogr am m ing Oracle Tr igger s and St ed Pr oced ur es-, Thinsert ir d Ed it ion , is an inv aluable r esou rce SQL> INSERT INTO temp SELECT *orFROM temp; 2 rows for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly executing temp_ais int ellig en t , com plex dat abases. [The Team LiB ] st at em en t f ires on ce p er SQL st at em ent . For t he last inser t a row t r ig ger w ould I NSERT hav e t o fir e t w ice. [ Team LiB ]

[ Team LiB ]

7.1 Sequence of Events You can d o t h e follow ing w it h an I NSERT STATEMENT t r igger : You can p er f orm an ag gr eg at e com put at ion on t he t able. This can be com put ed befor e or af t er t he in ser t . You can u se a st at ement level t r igg er t o pr ocess dat a t hat is collect ed by a r ow t r igger . This is cov er ed in Sect ion 7. 4 , " Pr ocessing Row Capt u red Dat a. " •

You canTable signofalContent an ev ent s . Th is can sim ply be a pr int st at em ent . I t can also be an em ail or

signal o aanot pr ocess u sing h e DBMS_ALERT Pr ogr am m ing tOr cl e ® her Tr i gger s and Stor e d Pt roce dure s, Thir d Edi tipack on age. By Kevin Owens

Figur e 7- 1 illust r at es t he behav ior of st at em ent lev el t r igger s t hat can p er f orm " Take Act ion " fu nct ions of " Rej ect t he Tr ansact ion" fu nct ions. The st at em en t lev el t rig ger has n o k now ledge of t he befor e and af t er values of an y ch anged r ow . For a com par ison w it h r ow t r igger s, er: Prent ice Hall PTR comPub parlish eFigur e 7- 1 w it h Figur e 6- 1 . Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

Figu r e 7 - 1 . St at e m e nt Le ve l Tr igge r .

Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Figur eDeclar 7- 1 illust es t he st s, at em ent lev el behav show s t h atk ey, r owch lev el , tand rig gers fir e at iv er at const r aint including p rim ar y ior. k ey ,I tu also nique, f or eign eck m uch bet w een m orteh e befor e- st at em ent and aft er - st at ement t r igger s. I f t hr ee row s ar e af fect ed b y a SQL UPDATE, as is t he ex amp le in t his fig ur e, t hr ee row t r ig ger s w ill fir e. St at ement lev el tPr r igger sm firing e onOracle ce. ogr am Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly [ Team LiB ] int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

7.2 Insert Statement Trigger Syntax The I n ser t St at em ent Trig ger has t h e follow ing syn t ax.

CREATE OR REPLACE TRIGGER trigger_name [AFTER | BEFORE] INSERT ON table_name DECLARE • Table of Content s Local declarations Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, BEGIN Body written PL/SQL By Kevin Owens END;

Thir d Edi ti on

Pub lish er: Prent ice Hall PTR

The Pub k eyDatdif en ce sy nt ax bet w een t he st at em ent an d row t r ig ger is t he FOR EACH e: fer Decem berin 0 5,t h2e 003 ROW clause—t his clause sp ecif ically ident if ies t h e t r igger as r ow lev el and is not in t h e I SBN: 0- 13 -0 850 33 -0 st at ement level t r igg er . Pages: 44 8

The st at em ent t rig ger syn t ax t hat desig nat es t he t r ig gerin g ev en t is t he sam e as r ow t r igger s. Refer t o Ch apt er 6, " Row Tr igger Sy nt ax , " f or a t hor ough discussion on t r igger nam ing conv en t ions an d t he OF COLUMN_NAME clause. The f ollow ing ar e v alid clauses for Efat fect ively level creat et r igg an derman com abases st ement s, asage w ell as plex r ow dat t r igg er s. w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor at e bu siness r ules wON hich ar e easy t o man age and m odif y as t he BEFORE INSERT ORporUPDATE OR DELETE table_name bu sin ess evolv es. Topics cov er ed include: AFTER INSERT OR UPDATE OF column_name OR DELETE ON table_name View in g const r aint s in t h e dat a dict ion ar y The f ollow in g ar e t wo k ey p oint s w it h r eg ard t o t r ig ger opt ion s: Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions

Tab le .

ALL ROW t r igg er s on ly .

WHEN (Boolean expression) I nt er - pr ocess com mu nicat ions Valid f or UPDATE ROW and STATEMENT t r igg er s only . Declar OF column_name at iv e const r aint clause s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e The sy nt ax f or st at em en t level t rigg er s is sim pler t han r ow t r igg er s. The follow in g feat ur es do Pr am mwing s and notogr exist it h Oracle st at em Tr enigger t level t r iggSteror s:ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. Ther e is no WHEN ( Boolean exp ression ) t h at v oids an y discu ssion of [ Team LiBCOLUMN_ ] OLD. NAME an d NEW. COLUMN_ NAME ex pr essions. Refer ences t o : NEW .COLUMN_NAME and : OLD. COLUMN_NAME ar e inv alid .

The comLiB binat [ Team ] ion of r ow an d st at em ent t rig gers is 12 t yp es of t rig gers. Th e follow ing sum m arizes t h e t emp lat e for each t r ig ger .

Tri gge r Ty pe

Tri gge ri ng Ev ent

BEFORE STATEMENT

Cre at e or R epl a ce ( e x am pl e : TEM P t a ble )

INSERT TRIGGER TEMP BEFORE INSERT ON TEMP BEGIN Body END

BEFORE EACH ROW [ a] •

INSERT

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d By Kevin Owens

TRIGGER TEMP BEFORE INSERT ON TEMP P roce dureFOR s, ThirEACH d Edi tiROW on BEGIN Body END

Pub lish er: Prent ice Hall PTR [ a ]0 5, Pub Dat e: Decem AFTER EACH ROWber

2 003 INSERT

TRIGGER TEMP AFTER INSERT ON TEMP Pages: 44 8 FOR EACH ROW BEGIN Body END Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t AFTER eaches STATEMENT you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. INSERT TRIGGER TEMP Using easy- t o- follow inst r uct ions an d ex am ples, t hisINSERT book pr esent s t echniq ues t o t ake AFTER ON TEMP adv ant ag e of Or acle feat ur es such as t rig gersBEGIN and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar eBody easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: END I SBN: 0- 13 -0 850 33 -0

b] a dict ion ar y ViewSTATEMENT in g const r aint sUPDATE in t h e [ dat BEFORE TRIGGER TEMP Com plex r ule enf orcem en t BEFORE UPDATE ON TEMP BEGIN PL/ SQL p r ogr am un it s and langu age f eat u res Body END Dat a t y pes and comp osit e st r u ct u re

Er r orEACH han dling except ions ] [b] BEFORE ROW [ aand UPDATE TRIGGER TEMP BEFORE UPDATE ON TEMP FOR EACH ROW Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch BEGIN m or e Body ENDur es , Th ir d Ed it ion , is an inv aluable r esou rce Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. I nt er - pr ocess com mu nicat ions

[ Team LiB ]

EACH [ AFTER Team LiB ] ROW[ a ]

UPDATE[ b ] TRIGGER TEMP AFTER UPDATE ON TEMP FOR EACH ROW BEGIN Body END

AFTER STATEMENT

UPDATE[ b ] TRIGGER TEMP AFTER UPDATE ON TEMP BEGIN Body END



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on BEFORE STATEMENT DELETE By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

TRIGGER TEMP BEFORE DELETE ON TEMP BEGIN Body END

I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 ROW [ a ] BEFORE EACH

DELETE

TRIGGER TEMP BEFORE DELETE ON TEMP FOR EACH ROW BEGINw it h Or acle! Sy st ems and dat ab ase ex per t Ef fect ively creat e an d man age com plex dat abases Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o Body t h e St r uct ur ed Query Langu age ( SQL) , an d ENDust an d com plex dat ab ases f or y our b usiness. t eaches you w hat y ou n eed t o kn ow t o build rob Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake AFTER EACH ROW[ a ] DELETE adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our TRIGGER TEMP dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he AFTER DELETE ON TEMP bu sin ess evolv es. Topics cov er ed include: FOR EACH ROW BEGIN Body View in g const r aint s in t h e dat a dict ion ar y END Com plex r ule enf orcem en t AFTER PL/STATEMENT SQL p r ogr am unDELETE it s and langu age f eat u res TRIGGER TEMP AFTER DELETE ON TEMP Dat a t y pes and comp osit e st r u ct u re BEGIN Body Er r or han dling and except ions END I nt er - pr ocess com mu nicat ions Declar iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch [ a] WHENat ( Boolean ex pression) is opt ional w ith all r ow tr igger s. m or e [ b] OF COLUMN_NAME clause is optional on UPDATE ROW and STATEMENT t rigger s. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for datgh abase d esign s, and oj gers, ect leader look intgy pe, t o bsuch uild an aint ain t r uly Alt hou t hisdtev abelopers, le illust r at es 12erdist inct pr t r ig an y tsr igger asdamBEFORE int ellig en t , com plex dat abases. STATEMENT t r igg er , can com b in e t r igger ing ev ent s such as t h e follow ing:

[ Team LiB ]

CREATE OR ]REPLACE TRIGGER temp_biuds [ Team LiB BEFORE INSERT OR UPDATE OR DELETE ON TEMP BEGIN CASE WHEN inserting THEN PL/SQL code here WHEN updating THEN PL/SQL code here WHEN deleting THEN PL/SQL code here END CASE; END;

[ Team LiB ] •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

7.3 Statement Level Aggregation St at em en t t r igg er s can en for ce bu siness r ules w here t he r ule is b ased on a t ab le aggr egat e. Alt hou gh a r ow t r igg er can r est r ain a salar y for a par t icular r ow , a st at em ent t rig ger can const r ain t h e r esult of SUM( salar y ) . This is essent ially a con st rain t on t he en t ire t able. This is q uit e dif fer en t f r om const rain t s discussed so far . I n it ially , simp le ru les are enf or ced w it h a CHECK const r aint . Ch apt er 6 illust r at es a m or e com plex ru le t hat r est r ict s t he salar y for any p rof essor in t he English depar t m en t w hile leavin g t h e CHECK const r aint t o enf orce a salary r est r ict ion for non- English p r ofessor s. follow r ules. •Con sider t heTable of ing Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

A p r ofessor cann ot b e added if t he cur r en t bu dget ex ceeds $ 55, 00 0.

By Kevin Owens

The t ot al bud get cannot exceed $6 0, 00 0. Pub lish er: Prent ice Hall PTR These can b e enfor ced w it h st at ement level t r igg er s. The f ir st t r igger , BEFORE STATEMENT, Dat e:any Decem ber 0 5, 2ion 003 t hat at t emp t s t o add a p rof essor w hen t he cu rr ent bud get ex ceeds w ill Pub r ej ect t r ansact I SBN: 013 -0 850 33 -0 $5 5, 000 . The AFTER STATEMENT t r igg er rej ect s t h e t r ansact ion w hen t he result of ad ding a pr of essor exceed s t he su m of $60 , 000. The d at a f or t he PROFESSORS t able in Ch apt er 4, Pages: 44 8 Sect ion 4. 4 , " Sam ple D at a, " show s t h e cur rent sum at $5 0, 000 . We could add a sing le pr of essor w it h a salary of $ 10, 0 00. Th is w ould pass t he business ru le t est . Howev er , t he BEFORE STATEMENT t rigg er w ill rej ect any add it ion al insert s.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Secon w e ex could in ser a salar of $ 5,answ 000 .erThis ld r buct e allow How ev er ,age t he( AFTER Kevin dly Ow,ens plor es PL/t SQL, Oryacle's t o twhou e St ur ed ed. Query Langu SQL) , an d STATEMENT t r igg er w ill lik ely r eject an y sizab le inser t aft er t h at . t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. The imeasyplem ten at ion of t hese business ruam lesples, will r tequir e t h eprfollow st ep s.ues t o t ake Using o-tfollow inst r uct ions an d ex his book esenting s t echniq adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin Updat ess evolv es.ERRORS Topics cov er ed e t he pack ageinclude: w it h er r or n um bers. En cap su lat e t he b usiness ru le log ic in a const r ain t s enf orcem en t pack age. View in g const r aint s in t h e dat a dict ion ar y Wr it e t he befor e and af t er st at em ent t r ig ger. Com plex r ule enf orcem en t The f ir st st ep is t o declar e er r or num b er s and m essag e t ex t in t he err or s pack age f r om un it rsaland u res Ch aptPL/ er SQL 6. Thpisr ogr is tam he cent d eflangu init ionage f or f eat er ror s r aised t h rou gh t he ap plicat ion . The ERRORS pack age is u pdat ed t o in clud e t w o er r or num b er s: – 200 02 and –20 003 . Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions CREATE OR at REPLACE errors pIS Declar iv e constPACKAGE r aint s, including rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch eng_dept_sal CONSTANT PLS_INTEGER := -20001; m or e app_error_02 CONSTANT PLS_INTEGER := -20002; PLS_INTEGER :=ur-20003; Pr ograpp_error_03 am m ing Oracle CONSTANT Tr igger s and St or ed Pr oced es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly eng_dept_sal_txt CONSTANT VARCHAR2(100) := int ellig en t , com plex dat abases. 'The salary exceeds the ENGL maximum of $10,000.00'; [ Team LiB ] app_error_02_txt CONSTANT VARCHAR2(100) := 'No additions if the budget exceeds $55,000.00';

app_error_03_txt CONSTANT VARCHAR2(100) := [ Team LiB ] 'Budget cannot be over $60,000.00'; END errors;

The n ex t st ep is t o en cap su lat e t he business log ic in a const r ain t s pack age. Such a p ack age w as dev elop ed in Ch apt er 6. We can r eviv e PROFESSORS_CONS. The f ollow ing show s t he pack age spec and b ody , m in us t h e pack age pr ocedur e code f r om Ch apt er 6. Th e follow ing code im plement s a single p r ocedu re t hat is used by t he BEFORE an d AFTER st at em en t t r igger . Ther e ar e sev eral st yles for cod ing t his. On e is t o m ak e a separ at e p rocedur e f or each t r igger . Wit h t his in t er f ace t he t r igger m u st pass t h e arg um ent s t h at specify t h e con st rain t limit , er r or code, and t ex t .



Table of Content s

Pr ogr am mOR ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d CREATE REPLACE PACKAGE professors_cons ISEdi ti on

PROCEDURE By Kevin Owens

constrain_budget (limit NUMBER,err_code PLS_INTEGER,err_text VARCHAR2); ENDPub professors_cons; lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

CREATEI SBN: OR 0REPLACE PACKAGE BODY professors_cons IS 13 -0 850 33 -0 PROCEDURE constrain_budget Pages: 44 8 (limit NUMBER,err_code PLS_INTEGER,err_text VARCHAR2) IS budget_sum NUMBER; Ef fectBEGIN ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, OrINTO acle'sbudget_sum answ er t o t hFROM e St r uct ur ed Query Langu age ( SQL) , an d SELECT SUM(salary) t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. professors; IF budget_sum > limit THEN Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake RAISE_APPLICATION_ERROR(err_code, err_text); adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our END IF; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he END constrain_budget; bu sin ess evolv es. Topics cov er ed include: END professors_cons; View in g const r aint s in t h e dat a dict ion ar y The BEFORE and AFTER st at em ent t r ig gers are t he last an d f inal st ep. As alway s, t h e body of t he t rig gerplex is shor an dorcem sim ple. Com r ulet enf en t Becau se b ot h I NSERT an d UPDATE st at em en t s can p ot ent ially v iolat e t he r ule, t h e t r ig ger in g ev ent is set t o I NSERT OR UPD ATE. PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions CREATE OR REPLACE TRIGGER professors_bis I nt er - pr ocess mu nicat BEFORE INSERT ORcom UPDATE ON ions professors BEGIN Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch professors_cons.constrain_budget m or e(55000, errors.budget_err_1, errors.budget_err_1_txt); Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce END; for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig enOR t , com plex dat abases. professors_ais CREATE REPLACE TRIGGER AFTER INSERT OR UPDATE ON professors [ Team LiB ] BEGIN professors_cons.constrain_budget (60000, errors.budget_err_2, errors.budget_err_2_txt);

END; [ Team LiB ] I f t hese ru les are in place ( i. e., t he p ack ages and t r igg er com pile) w e can inser t t his n ex t pr of essor:

INSERT INTO professors VALUES ('Smith', 'Mathematics', SYSDATE, 10000.00, 'YES','MATH');

How ev er , any f ur t her I NSERTs w ill be r eject ed by t he BEFORE st at em en t t rigg er . Th is is du e •t o t he f act t hat Table of Content t he cu rr ents SUM( SALARY) ex ceeds $55 ,0 00. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

We canOwens inser t t his p rof essor : By Kevin

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 0- 13 -0 850 33 -0 INSERTI SBN: INTO professors VALUES Pages: 44 8 ('Smith', 'Mathematics', SYSDATE, 5000.00, 'YES','MATH');

How evively er , any sizable ditage ion tcom o t hplex e st aff ill passwt h v alid in and t h e BEFORE Ef fect creat e an d ad man datwabases it e h fir Orst acle! Syatstion ems dat ab ase ex per t st at ement t r igger ( t es he PL/ bu dget $ 55,answ 00 0) ,erb ut ej ect ed Query by t h eLangu second , t he AFTER Kevin Ow ens ex plor SQL, isOrat acle's t o will t h e bSter ruct ur ed age ( SQL) , an d st at ement ou ld e salar of tan h isd addit ion caused t h e SUM( SALARY) to t eaches yout r igger w hat . yThis ou n w eed t o occur kn ow ift ot hbuild roby ust com plex dat ab ases f or y our b usiness. exceed $ 60, 00 0. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our [dat Team LiBt o ] incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he ab ases bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

7.4 Processing Row Captured Data Row t r ig gers can st or e : OLD an d : NEW colum n v alu es in a global t em por ar y t ab le. Th e scop e of a g lobal t em por ar y t able is j ust t hat t ran sact ion. By copy in g : OLD and : NEW v alu es, t he pr ocessing of t he b usiness ru le can be defer red t o t he st at ement level t r igg er . Som et im es t his is necessar y because t he b usiness r u le is com plex and r equir es quer ies fr om t ab les, includin g t he t able being up dat ed. The f ollow in g illust r at es t he general t echn ique. First a g lob al t em por ar y t able is needed. Th is t able w ill b e used t o st or e dat a in t h e r ow lev el t r igg er . •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE global temporary TABLE professors_g (prof_name VARCHAR2(10), Pub lish er: Prent ice Hall PTR specialty VARCHAR2(20), Pub Dat e: Decem ber 0 5, 2 003 hire_date DATE, I SBN: 0- 13 -0 850 33 -0 salary NUMBER(7,2), Pages: 44 8 tenure VARCHAR2(3), department VARCHAR2(10)) ON COMMIT DELETE ROWS;

The Ef fect n ex ively t stcreat ep is et oancod d man e pr age ocedcom ur esplex in t hdat e const abases r ainwtitshpack Or acle! age fSy or stt his emst able. and dat These ab ase ex per t Kevin pr ocedOw ur es ens w ill ex be ploradd es PL/ ed tSQL, o t heOr PROFESSORS_ acle's answ er CONS t o t h e packag St r uct ur e. ed Show Query ing Langu just t he age ad( dit SQL) ions , an f ord t he eaches packag youe w specif hat yicat ou ion: n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: CREATE OR REPLACE PACKAGE professors_cons IS PROCEDURE load_temp_table View(v_prof_name in g const r aint s inprofessors.prof_name%TYPE, t h e dat a dict ion ar y v_specialty professors.specialty%TYPE, Com plex r ule enf orcem en t v_hire_date professors.hire_date%TYPE, v_salary professors.salary%TYPE, PL/ SQL p r ogr am un it s and langu age f eat u res v_tenure professors.tenure%TYPE, v_department professors.department%TYPE); Dat a t y pes and comp osit e st r u ct u re PROCEDURE dump_temp_table; Er r or han dling and except ions END professors_cons; I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch The pm ackag or e e body is: Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. CREATE OR ]REPLACE PACKAGE BODY professors_cons IS [ Team LiB PROCEDURE load_temp_table (v_prof_name professors.prof_name%TYPE,

professors.specialty%TYPE, [ Team LiBv_specialty ] v_hire_date professors.hire_date%TYPE, v_salary professors.salary%TYPE, v_tenure professors.tenure%TYPE, v_department professors.department%TYPE) IS BEGIN INSERT INTO professors_g VALUES (v_prof_name, v_specialty, v_hire_date, v_salary, v_tenure, v_department); END load_temp_table; PROCEDURE dump_temp_table IS BEGIN FOR rec in (SELECT * FROM professors_g) LOOP dbms_output.put_line( • Table of Content s rec.prof_name||' '||rec.specialty||' '|| Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on rec.hire_date||' '||rec.salary||' '|| By Kevin Owens rec.tenure||' '||rec.department); END LOOP; END dump_temp_table; lish er: Prent ice Hall PTR ENDPub professors_cons; Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

The f ollow g 8is a AFTER DELETE ROW t r igger . When t his t r igg er fir es it only in ser t s r ow dat a Pages:in44 in t he t em por ar y t able t h rou gh t he PROFESSORS_ CONS packag e.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tCREATE eaches you w hat y ou TRIGGER n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. OR REPLACE professors_adr AFTER DELETE ON professors Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake FOR EACH ROW adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our BEGIN dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he professors_cons.load_temp_table bu sin ess evolv es. Topics cov er ed include: (:old.prof_name, :old.specialty, :old.hire_date, :old.salary, :old.tenure, :old.department); END; View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t The n ex t t r ig ger is an AFTER DELETE STATEMENT t r igger t h at uses t he con st raint s packag e t o pr int PL/ t heSQL r ow sp rdogr eletam ed.un Altithou gh langu t his dage em onst ion m er ely pr int s t h e dat a, in som e s and f eat ruat res circum st ances t his can be u sef ul t o a st at em en t lev el t rig ger. St at ement lev el t r igger s hav e a t ge y pes comp osit e ed st r ubct re SQL st at em ent . Th ey h ave no k now ledge of : OLD no knDat ow led of and t he row s af fect y ut he and : NEW v alues. Er r or han dling and except ions The AFTER DELETE st at em en t t r igg er is: I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce CREATE ORing REPLACE TRIGGER professors_ads for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly AFTER DELETE ON professors int ellig en t , com plex dat abases. BEGIN professors_cons.dump_temp_table; [END; Team LiB ]

The D ELETE SQL st at em ent is follow ed by t he ou t put fr om t he st at ement t r igger .

[ Team LiB ]

SQL> DELETE FROM professors; Blake Mathematics 08-aug-2003 02:06:27 10000 YES MATH Milton Am Hist 09-aug-2003 02:06:27 10000 YES HIST Wilson English 06-aug-2003 02:06:27 10000 YES ENGL Jones Euro Hist 12-jul-2003 02:06:28 10000 YES HIST Crump Ancient Hist 12-jul-2003 02:06:28 10000 YES HIST 5 rows deleted.

[• Team LiB ] Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Chapter Eight. Complex Rule Enforcement The f ollow in g scenar io is based on t h e dat a in t he STUDENT_VEHI CLES t able an d t he PARKI NG_TI CKETS t ab le. Ref er t o Ch apt er 4, Sect ion 4. 4 , f or t he sam ple d at a. A b usiness ru le can som et im es hav e a recur siv e n at ur e. A g en er al scen ario is w hen an UPDATE st at em ent ex ecu t es and an upd at e t r igger m odif ies ot h er row s in t h at sam e t able. Delet es can also be r ecur siv e. Cer t ainly, t he f or eign k ey delet e cascade is on e met h od of dat a. Ot •delet in g dependent Table of Content s her t im es, t he b usin ess r ule is com plex and a delet e t r igg er mu st progr Pr oced amur m ally ing Or det a clerm e ® Tr ine i gger if sad and ditStor ional e d dPelet rocees dure ars,eThir requ d Edi ired. ti on By Kevin Owens

The f ollow in g scenar io dem onst r at es a r ecu rsiv e delet e. Th e delet e row t r igger m ay delet e add it ion al r ow s. I t m ay not . I t depend s on t he d at a. The business ru le is: Pub lish er: Prent ice Hall PTR

When a st u dent p ays a par k ing t icket , all ot her t icket s f or t he sam e car and f or t he sam e amou nt are delet ed as w ell, p r ovided t he su m of t he t ick et s t o b e delet ed does not I SBN: 0-$13 -0 850 exceed 10. 00 33 . -0

Pub Dat e: Decem ber 0 5, 2 003

Pages: 44 8

The r at ion ale is t hat t ick et s ar e somet im es dup licat ed. Th e assu m pt ion is t hat mu lt iple t icket s for t he sam e am ount and t h e sam e car ar e accident al d uplicat es. I f t h e sum of t h e t ick et s is excessiv e, t hen t his is pr ob ably not t he case. Hen ce t he lim it of $1 0. 00. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t A st u dent canex hav e es t h ree ick et s, 00 .erAllt oart heedelet edurwed henQuery one tLangu ick et is paid. The, an d Kevin Ow ens plor PL/ tSQL, Or each acle's$3. answ St r uct age ( SQL) Ch apt er 4 sh ows t hat t her e is one case of t his. The dat a fr om t he Par kin g Tick et s t able in t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. v eh icle w it h New Yor k t ag num ber MH 87 09 has a dup licat e p ark ing v iolat ion . Each t icket is $5 .0 0.easyAccort oding t o t inst his rr ule, onean p aid delet es book b ot h par kin g st ick et s fr ues om tt ho et ake t able. Using follow uct ions d ext ick amet ples, t his pr esent t echniq adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Theab t ask dev elop t hatr ules t ak es t he specif ic act t oage delet e add it ion dat asesis t too incor por ata et rig bu ger siness w hich ar e easy t oion man and m odif y al asr ecor t he ds w it hin t he sam e t ab le. A ROW t r igger cann ot r ead or perf or m any D ML operat ion on t he t able bu sin ess evolv es. Topics cov er ed include: being m odified. The r eason is t he t able is being up dat ed. Oracle gu ar ant ees con sist ent reads by q uer ies r ead fr om r ollb ack segm ent s. Th e SELECT or any DML operat ion w it hin t he cont ex t of a r View ow t rig gener atsesinan ORA049 in gger const r aint t h Oracle e dat a dict ion ar y1 Tab le Mut at in g er r or. The ap pr oach t hese sit uat ions Com plex in r ule enf orcem en t is t o capt u re row valu es t hat ar e n eeded t o enf or ce t he bu sin ess r ule an d m ak e t hem av ailable t o an AFTER st at em en t t r igg er . Ch apt er 7 end ed w it h p r ogr it sTh and languing ageisf eat an ex PL/ am SQL ple sim ilaram t o tun h is. e follow a f uirres st st ep at t hat pr ocess. The p ackag e below is designed t o capt u r e t he STATE, TAG_NO, and AMOUNT f r om t he ROW t rig ger. This dat a is pesaland ositt able. e st r uThe ct u ref ollow in g is t h e defin it ion of t h e global t em por ar y st or edDat in aa tgy lob t emcomp por ary t able. Upon a com m it or r ollback , dat a is clear ed f r om t he t able. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m orGLOBAL e CREATE TEMPORARY TABLE parking_tickets_g (state VARCHAR2(2), Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce tag_no VARCHAR2(10), for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly amount NUMBER) ON COMMIT DELETE ROWS; int ellig en t , com plex dat abases. [ Team LiB ] The n ex t st ep is a packag e t hat int er faces w it h t h e r ow and st at em en t t r igg er , show n in Figur e 8- 1 . Th e r ow t r igger w ill pass v alues in a pr ocedur e call. Those v alues ar e inser t ed int o t he g lobal t em por ar y t able. The st at em ent lev el t r ig ger calls a pr ocedur e t h at r eads t h e r ow level d at a f rom t he t em por ar y t able an d en for ces t h e bu siness r ule.

[ Team LiB ]



Figu r e 8 - 1 . Pa r k in g Ti ck e t D el et es Ar ch it e ct ur e .

Table of Content s

Pr ogrfam m ing Oris a cltehe ® Tr i gger sicat andion Stor e ddPbroce ti on The ollow in g specif an odydure of s, t hThir e t rdigEdi ger int er face

pack age. This is called t h e PARKI By KevinNG_TI Owens CKETS_CONS pack age. This code accept s r ow d at a f r om t he r ow t rig ger. For st at ement level p rocessing it sim ply p rint s t he d at a r ead fr om t h e t em p orar y t ab le. This w ill be r ev ised sh ort ly t o includ e t he d elet es. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

CREATE OR REPLACE PACKAGE parking_tickets_cons IS PROCEDURE load_temp_table Ef fect ively(v_state creat e an dparking_tickets.state%TYPE, man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor esparking_tickets.tag_no%TYPE, PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d v_tag_no t eaches youv_amount w hat y ou parking_tickets.amount%TYPE); n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. UsingPROCEDURE easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake remove_duplicates; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our END parking_tickets_cons; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: The p ackag e body is: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res CREATE OR REPLACE PACKAGE BODY parking_tickets_cons IS PROCEDURE load_temp_table Dat a t y pes and comp osit e st r u ct u re (v_state parking_tickets.state%TYPE, parking_tickets.tag_no%TYPE, Er r or v_tag_no han dling and except ions v_amount parking_tickets.amount%TYPE) IS I nt er - pr ocess com mu nicat ions BEGIN Declar INSERT at iv e const INTOr aint parking_tickets_g s, including p rim ar VALUES y k ey , u nique, f or eign k ey, ch eck , and m uch m or e (v_state, v_tag_no, v_amount); END load_temp_table; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and PROCEDURE remove_duplicates ISpr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. BEGIN FOR rec in(SELECT * FROM parking_tickets_g) LOOP [ Team LiB ] dbms_output.put_line ('REC:'||rec.state ||' '||rec.tag_no||' '||rec.amount); END LOOP;

ENDLiB remove_duplicates; [ Team ] END parking_tickets_cons;

The r ow t rig ger w ill call t he af orem ent ioned pr oced ur e LOAD _TEMP_ TABLE. The st at em en t level t r igg er w ill call REMOVE_DUPLI CATES, w hich f or now pr int s t h e r ows select ed fr om t h e t em por ary t able. The r ow and st at em ent lev el t r igger s ar e:

CREATE OR REPLACE TRIGGER parking_tickets_adr AFTER DELETE ON parking_tickets •FOR EACH ROW Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on BEGIN parking_tickets_cons.load_temp_table By Kevin Owens (:old.state, :old.tag_no, :old.amount); END; Pub lish er: Prent ice Hall PTR

CREATE OR REPLACE parking_tickets_ads Pub Dat e: Decem ber 0 5,TRIGGER 2 003 AFTER I DELETE ON parking_tickets SBN: 0- 13 -0 850 33 -0 BEGIN Pages: 44 8 parking_tickets_cons.remove_duplicates; END;

creat d man dat, abases w it h in Orfor acle! ems IEff fect w e ively ex ecut e t hee an follow ingage SQLcom st atplex em ent t he v ehicle m atSy ionstis p r inand t ed .dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor at e bu siness r ules w hich ar e easy t o man age and m odif y as t he SQL> DELETE FROMporparking_tickets bu sin evolv es. Topics cov er ed include: 2 ess WHERE ticket_no = ='P_02'; REC:NY MH 8709 5 View in g const r aint s in t h e dat a dict ion ar y 1 row deleted. Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res The f inal st ep is t o r ev ise t h e logic in REMOVE_D UPLI CATES. This p r ocedu re m u st qu er y t h e PARKIDat NG_STUDENTS t ableosit t o edet a t y pes and comp ster r umine ct u re if t here ar e ot her r ows for t h e same vehicle and sam e t ick et am oun t . Er r or han dling and except ions On e row is already delet ed. To det er min e if t he sum of t ick et s is w it hin t he $ 10. 00 r ange, t he t icket I nt amou ntocess ( of t he d elet ed r ow ) mu st be added t o t h e SUM( am ount ) lef t in t h e t able. The er - pr com mu nicat ions r ev ised REMOVE_ DUPLI CATES is t he f ollowin g: Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly PROCEDURE remove_duplicates int ellig en t , com plex dat abases. IS [ Team ct LiB NUMBER; ] BEGIN FOR rec in (SELECT * FROM parking_tickets_g) LOOP

SELECT [ Team LiB ] FROM WHERE AND AND

SUM(amount) INTO ct parking_tickets state = rec.state tag_no = rec.tag_no amount = rec.amount;

ct := ct + rec.amount; IF ct SELECT * FROM parking_tickets; TICKET_NO AMOUNT ST TAG_NO Ef fect ively creat e an d man -age ---------com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t ------------------Kevin Or acle's P_01 Ow ens ex plor es PL/ 5 SQL, CA CD 2348 answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tP_02 eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 5 NY MH 8709 P_03 5 NY MH 8709 Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake P_04 5 NY JR 9837 adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he SQL> DELETE FROM parking_tickets WHERE ticket_no='P_02'; bu sin ess evolv es. Topics cov er ed include: SQL> SELECT * FROM parking_tickets; View in g const r aint s in t h e dat a dict ion ar y TICKET_NO AMOUNT ST TAG_NO -----------en---------Com plex---------r ule enf orcem t P_01 5 CA CD 2348 P_04 PL/ SQL p r ogr am un5it sNYand JRlangu 9837age f eat u res Dat a t y pes and comp osit e st r u ct u re The af t er st at ement t r igger includ es a DELETE st at em en t on t he t able fr om w h ich t he orig in al delet eErwr or as han appdling lied. and except ions I ntLiB er - pr [ Team ] ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Chapter Nine. The PL/SQL Environment 9. 1 A HELLO WORLD PROGRAM 9. 2 REFERENCI NG ORACLE PACKAGES 9. 2. 1 Cr eat ion of t he En vir onm ent 9. 2. 2 The API 9. 3 USER_OBJECTS •

Table of Content s

Pr ogr am mDEPENDENCI ing Or a cl e ® Tr i gger s and StorPROCEDURES e d P roce dure s, Thir d Edi ti on 9. 4 ES AMONG By Kevin Owens

9. 5 USER_D EPEND ENCI ES 9. 6 USER_SOURCE

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

9. 7 SHARI NG CODE I SBN: 0- 13 -0 850 33 -0

9. Pages: 8 COMPI 44 8 LATI ON DEPENDENCY 9. 8. 1 Scen ario 1 9. 8. 2 Scen ario 2 Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin9.Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 9 USER_ERRORS t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. For t r adit ional com piler langu ages, such as C, w e w r it e our sou rce code an d t hen com pile it . Using easyt o- follow ions an ex am ples, t hiscom book prion esent t echniq t o t ake We m ay choose f rom inst oner uct of sever al dcomp iler s. The pilat pr soduces a ues second file—an adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t y our obj ect file. We t h en use a lin ker t o link one or m ore object s int o an ex ecu t able. hat Theallow com pile dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he and link p rocess leav es us w it h our sou rce, sev eral obj ect files, an d an ex ecut able im age t hat bu sin ess ed evolv cov edt he include: is execut undes. er Topics t he cont r olerof oper at ing syst em . The f inished p rog ram m ay use some syst em libr ar y fu nct ions t h at p er for m ser vices such as file open, p ut lin e, and file close. View in g const r aint s in t h e dat a dict ion ar y The PL/ SQL m odel is dif fer en t an d sim pler fr om t r ad it ion al pr ogr am m ing, as ju st descr ibed. Wit h PL/ SQL, ar torcem w it h w Com plex yrou ulestenf enr it t ing y our ow n sour ce using a " SQL" f ilenam e ex t ension . On ce y ou h ave t he ASCI I t ex t file w it h a " SQL" ex t en sion y ou com pile it , b ut t hink of Oracle as y our com piler . Or acle comp e and f or syn t ax err or s. Aft er t he com pile, y ou PL/ SQL p r ogr am iles un it sy our and cod langu agecheck f eat usres hav e no add it ion al f iles—t her e is no object f ile follow ing t he com pile. The equ iv alent of t he obj ectDat and ablecomp im age t hat is st or ed in t he d at abase dat a dict ionar y. a texecut y pes and ositise Pst rcod u cteu re Add it ion ally , Oracle st or es t he sour ce code y ou just com piled in t h e dat a dict ionar y. Er r or han dling and except ions Ther e ar e I nt eract iv e Dev elopm ent Env ir onm ent ( I D E) op t ions t o coding w it h a t ext edit or , includin Pr oced Builder, I ntgerOracle - pr ocess com ur muenicat ions w hich p rov ides a gr aphical u ser int er face ( GUI ) f or creat ing , edit ing, and comp ilin g b ot h client - and ser v er - side PL/ SQL. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e [ Team LiB ] Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

9.1 A Hello World Program The t ex t in t h is session includ es scr een oupu t f r om SQL* Plus sessions. Ref er t o Ch apt er 2 f or hint s and use of SQL* Plus com m ands. Th e follow ing t able list s t he com m on SQL* Plu s com man ds used in t h is chapt er .

SQL* Plus com m a nd SAVE filename •

@filename

D e scri pt i on Sav es t he SQL* Plus b uff er t o a file w it h an SQL ex t ension

Table of Content s

Sends t he f ile t o Or acle for com pile/ ex ecu t ion. You do not need t o t y pe t h e " . SQL" ext ension.

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

SET SERVEROUTPUT ON /

Set s up DBMS_ OUTPUT t o f lush t he bu ff er t o t h e scr een .

Pub lish er: Prent ice Hall PTR

Sends t he SQL* Plus b uff er t o Oracle f or comp ile/ ex ecut ion .

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

From SQL* Plu s, t y pe t he follow ing Hello W orld pr ogr am . First , t yp e t he SQL* Plus com m and Pages: 44 8 SET SERVEROUTPUT ON, t h en t h e pr oced ur e t ext . The last line is a for w ar d slash—t his is SQL* Plus an d in st r uct s SQL* Plu s t o send t he t yp ed t ex t t o Or acle t o be com piled.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. SQL> SET SERVEROUTPUT ON Using easy- t o- OR follow inst r uctPROCEDURE ions an d exhello am ples,ISt his book pr esent s t echniq ues t o t ake SQL> CREATE REPLACE adv2antBEGIN ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat3ab ases tDBMS_OUTPUT.PUT_LINE('Hello'); o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu 4 sin ess evolv es. Topics cov er ed include: END; 5 / View in gcreated. const r aint s in t h e dat a dict ion ar y Procedure Com plex r ule enf orcem en t SQL> execute hello Hello PL/ SQL p r ogr am un it s and langu age f eat u res PL/SQL completed. Datprocedure a t y pes and successfully comp osit e st r u ct u re Er r or han dling and except ions Use t he DBMS_ OUTPUT packag e for st an dar d out pu t . The DBMS_OUTPUT p ack age h as ov er loaded process oced ur es for d if ferions en t d at at y pes: DATE, NUMBER, an d VARCHAR. Th e pack age I nt er - pr com mu nicat specif icat ion f or t he PUT_LI NE pr ocedur e is Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly procedure put_line VARCHAR2); int ellig en t , com plex dat(arg abases. procedure put_line (arg NUMBER); [ Team LiB ]put_line (arg DATE); procedure

You m ust ex ecut e t he SQL* Plus com m and once f or each session if y ou use DBMS_ OUTPUT.

[ Team LiB ]

SET SERVEROUTPUT ON

DBMS_ OUTPUT buf fer s out p ut t o a session - sp ecific D BMS_OUTPUT bu ff er . Each call t o t he PUT_LI NE pr oced ur e does not im mediat ely du mp t ex t t o y our screen—it st ay s in t he buf fer . The SET SERVEROUTPUT ON comm an d d irect s t he SQL* Plu s session t o du mp bu ff er ed t ex t t o y our screen upon com plet ion of a pr ogr am . The d ef ault buf fer size is 20 ,0 00 char act er s. You can incr ease t his w it h a call t o t he ENABLE pr oced ur e in DBMS_OUTPUT. The max im um is 1 ,0 00, 0 00 ch aract er s. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

SQL> execute dbms_output.enable(1000000); PL/SQL completed. Pub lishprocedure er: Prent ice Hallsuccessfully PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

The con t en t of t h e SQL* Plus bu ff er is cu rr ent ly t h e Hello pr ogr am . List t he SQL* Plus b uff er Pages: 44 8 ( low er case L) an d sav e ( SAVE) it t o a f ile.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches SQL> l you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 1 CREATE OR REPLACE PROCEDURE hello IS Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 2 BEGIN adv3ant ag e dbms_output.put_line('Hello'); of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat4* ab ases t END; o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SQL> save hello Created file hello SQL> View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t You ju st saved t he cont en t s of t he SQL* Plus buf fer t o a h ost file HELLO. SQL. Ru n t he script . This rPL/ ecomp t h eam HELLO r ocedu re. age f eat u res SQLiles p r ogr un it spand langu Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SQL> I @hello.sql nt er - pr ocess com mu nicat ions Procedure created. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e IPrf ogr youam t r ymting o creat Oracle e a Tr t able iggeran s dand it ex Stist or s, ed an Pr oced er r orurcom es , es Th bir ack d Ed . To it ionr ecr , iseat aneinv a taluable ab le your esou m ust rce for fir stdat d rop abase t h e dt ev able elopers, an d t hen d esign cr eat er s, e itand . This pr oj p rev ect ent leader s accid s look en tin algr ecr t o beat uild inganofd amtaint ab leain w itt rhuly v it al int datellig a. St enort ,edcom pr ocedur plex dat esabases. hav e a CREATE OR REPLACE syn t ax t h at is consist en t w it h m ost pr ogr am m ing langu ages. This syn t ax creat es t he pr ocedu r e if it does not exist ; if it does [ Team LiB ] r ecom piles it . exist , Oracle Ed it t h e file HELLO. SQL and insert inv alid sy nt ax . Ch ange PUT_ LI NE t o PUTLI NE. Add t w o add it ion al lines at t he end. Add a SQL* Plus com m and , SHOW ERRORS; t hen ad d t he

SQL* Plus [ Team LiBLI]ST ( L) comm and . The ed it ed file, sev en lin es lon g, is t h e follow ing:

CREATE OR REPLACE PROCEDURE hello IS BEGIN dbms_output.putline('Hello'); END; / show errors l

Ru n t he com man d f ile w it h @HELLO. This w ill ( a) comp ile t he pr ocedur e w it h err or s; ( b) •execut e t h e Table Content s SQL* of Plus SHOW ERRORS com m and , w hich will list t he of fending line of PL/ SQL Pr ogr am m ing Or a cl e ® Tr i gger s d Pt roce s, Thired jEdi code; an d ( c) pr ov id e a f ulland listStor ing eof he pdure rocedur ustti on com piled w it h t h e SQL* Plu s LI ST com By Kevin man Owens d.

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

SQL> @hello

Pages: 44 8

Warning: Procedure created with compilation errors. Errors for PROCEDURE HELLO: Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d LINE/COL ERROR t-------eaches you-----------------------------------------------w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 3/5 PL/SQL: Statement ignored Using t o- follow instcomponent r uct ions an d'PUTLINE' ex am ples, must t his book pr esent s t echniq ues t o t ake 3/17 easy-PLS-00302: be declared adv1antCREATE ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our OR REPLACE PROCEDURE hello IS dat2ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he BEGIN bu 3 sin ess evolv es. Topics cov er ed include: dbms_output.putline('Hello'); 4* END; View in g const r aint s in t h e dat a dict ion ar y Cor r ect t he h ost f ile, HELLO. Com plex r ule enf orcem SQL, en t and r eplace PUTLI NE w it h PUT_ LI NE. Comp ile an d ex ecu t e. Sup pr ess SQL* Plus feed back m essages w it h SET FEEDBACK OFF: PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SQL> set feedback off SQL> I @hello nt er - pr ocess com mu nicat ions No errors. at iv ehello const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch SQL> Declar execute Hellom or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig t , com dattabases. Cr eat e en a PL/ SQLplex block hat inv ok es t he HELLO pr oced ur e. Do t h is by cr eat in g a t ext f ile w it h a SQL ex t ension. Nam e t he file RUN_HELLO. SQL. The f ollowin g illust r at es t he sy nt ax f or a [PL/ Team ] ( t he f orw ar d slash is t he SQL* Plu s comm and t o comp ile and ex ecu t e t he SQL LiB b lock scr ipt ) .

[ Team LiB ] DECLARE Variables BEGIN Body of PL/SQL code. END; /

The D ECLARE par t is op t ional; it is not necessary if t he block uses no var iables. A PL/ SQL block is dif fer en t f rom a st or ed p rocedur e. HELLO is a com piled ob ject in t he dat ab ase. You m ust fir st com pile HELLO. SQL; t hen you can ex ecut e t h e pr oced ur e. RUN_HELLO.SQL, show n nex t , is sev en lin es lon g an d in clu des a com m en t an d a •The t ex t for Table of Content s for w ar d slash in t he last line. This is a PL/ SQL b lock . I t ex ecu t es t he HELLO pr ocedur e f iv e Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on t im es. By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

-- Filename: I SBN: 0- 13 -0 RUN_HELLO.SQL 850 33 -0 BEGINPages: 44 8 FOR run_count IN 1..5 LOOP hello; END LOOP; END; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t / Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. A sing le comt om follow and t o inst comr uct p ileions an dan exdecu t e aples, PL/ SQL is:esent s t echniq ues t o t ake Using easyex am t his block book pr adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: @filename -- rthe View in g const aint sSQL in t hfile e dat extension a dict ion ar y is not necessary Com plex r ule enf orcem en t Building t h e HELLO pr ocedu re in clu des t w o st eps: PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re 1 . First , y ou comp ile HELLO. SQL—t h is st ep v alid at es t he lang uage sy nt ax and com p iles t h e sour in dling t h e dat ab ase. Er r orcehan and except ions 2 . The st ep ismu t o nicat ex ecuions t e t he pr ocedu r e. I nt ersecond - pr ocess com You build t he PL/ w itincluding h one st ep: ex ecuf or t e.eign To rkun e eck PL/ ,SQL Declar at iv e SQL constblock r aint s, p rimcom ar ypilek ey and, u nique, ey,t hch andblock m uchin SQL* Plus: m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. SQL> [ Team@run_hello LiB ] Hello Hello Hello

Hello [ Team LiB ] Hello

Use PL/ SQL block s as t est dr iv er s f or st or ed pr ocedur es. There is not hin g d if fer ent ab out t he code in a PL/ SQL block and t he cod e in st or ed p r ocedu re—bot h u se PL/ SQL. En hance t est dr iv er cod e w it h ex cept ion h andling code t o display an ex cept ion er r or nu mb er and err or m essage. Th e PL/ SQL block b elow in clud es a WHEN OTHERS except ion han dler t hat pr int s t h e except ion t o a du plicat e in ser t . Fir st , cr eat e a t able w it h a pr im ar y key const r aint .

CREATE TABLE TEMP(N NUMBER CONSTRAINT PK_TEMP PRIMARY KEY); •

Table of Content s

Pr ogr amTEMP. m ing Or a cl eis ® tTr i gger s and P roce dure s, Thir d Ediincludes ti on TEST_ SQL he nam e ofStor t hee dPL/ SQL block and

an except ion han dler . I n cont ains 11 lin es, includ ing an in it ial com m ent and a f orw ar d slash as t h e last line, w hich By Kevin Owens m ust b e in Colum n 1. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 -- Filename: TEST_TEMP.SQL BEGIN INSERT INTO temp VALUES (1); INSERT INTO temp VALUES (1); Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t EXCEPTION KevinWHEN Ow ens ex plorTHEN es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d OTHERS t eaches you w hat y ou n eed t o kn ow t o buildcode:'||SQLCODE||'***'); rob ust an d com plex dat ab ases f or y our b usiness. dbms_output.put_line('Error dbms_output.put_line Using easy- t o- ('Error follow instmessage:'||SQLERRM||'***'); r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our END; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he / bu sin ess evolv es. Topics cov er ed include:

I n t his PL/ SQL block , t h e second inser t f ails w it h a pr imar y k ey con st rain t v iolat ion . The cod e View in g const r aint s in t h e dat a dict ion ar y in t he ex cept ion han dler uses DBMS_OUTPUT t o pr int t he er r or num b er an d message. Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re SQL> @test_temp ErrorEr code:-1*** r or han dling and except ions Error message:ORA-00001: unique constraint (SCOTT.PK_TEMP) violated*** I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch PL/ SQL b lock m or e s conv ert t o st or ed pr ocedu r es b y add in g CREATE OR REPLACE. The f ollowin g pr oced ur e, TEST_TEMP, im plem en t s t he p r eceding scr ipt as a com piled pr ocedu re in t h e Pr ogr m ing Tr igger s andaStcor or red ur es , stTh d Ed , isw an inv aluable dat abam ase. Th eOracle follow ing includes ectPr edoced I NSERT atirem entit ion t hat ill not v iolat e trhesou e rce for abase d ev elopers, pr imdat ary key const r aint . d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

-- Filename: TEST_TEMP.SQL

CREATE OR ]REPLACE PROCEDURE TEST_TEMP IS [ Team LiB BEGIN INSERT INTO temp VALUES (1); INSERT INTO temp VALUES (2); EXCEPTION WHEN OTHERS THEN dbms_output.put_line('Error code:'||SQLCODE||'***'); dbms_output.put_line ('Error message:'||SQLERRM||'***'); END; /

[ Team LiB ] •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

9.2 Referencing Oracle Packages Each langu age has sy nt ax for r efer en cin g ot her pr ogr am u nit s. The C pr ogr am m ing langu age uses an I NCLUDE dir ect iv e t o r efer en ce header files.

#include #include •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Perl scrOwens ipt s call p rocedur es in t he Win dow s32 lib rar y w it h a USE WI N32 dir ect iv e. By Kevin

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 use Win32::Registry; Pages: 44 8 use Win32::OLE;

Jav a classes im por t w h ole packag es and packag e classes. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake package adv ant ag eproject.students; of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our import java.io.*; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he import bu sin essjava.util.*; evolv es. Topics cov er ed include: import java.sql.*; import oracle.sql.*; View in g const r aint s in t h e dat a dict ion ar y import oracle.jdbc.*; import project.util.*; Com plex r ule enf orcem en t PL/ SQL r ogr am it sment and s,langu f eatt u Wit h each of tphese envun iron it is age a t ask o res locat e t he lib rar y code y ou need an d mak e sur e it is in y our p at h. PL/ SQL does not r eq uir e a com piler dir ect iv e t o u se ot her pack ages. I f pes st r u ct y ou wDat an tat ot y w r it eand PL/ comp SQL tosit h at euses t huereDBMS_OUTPUT p ack age, or anot her Or acle PL/ SQL pack age, y ou sim ply w r it e t he pr ocedu re call in y our code. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions

9.2.1 Creation of the Environment

Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e The d at abase adm inist r at or com piles man y PL/ SQL p ack ages int o t he Or acle SYS accou nt . This is p art of cr eat ing t h e dat ab ase. Th e dat ab ase cr eat ion p rocess also creat es pu blic Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce syn ony m s and pub lic gr ant s f or t h ese pack ages. Nat ur ally, som e p ack ages ar e int end ed f or for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Or acle int ern al use an d h ave rest r ict ed access. int ellig en t , com plex dat abases. These pack ages pr ov id e a r obu st App licat ion Pr ogr amm ing I nt er face ( API ) . You can use t he [ Team LiB ] Or acle API t o develop PL/ SQL pr oced ur es t hat use m et hods in Jav a classes, w r it e t o h ost files, sen d mail t hr ough an SMTP ser vice, and m any ot h er fun ct ion s. As y ou w rit e PL/ SQL y ou d isp lay out pu t u sing t h e DBMS_ OUTPUT p ack age. Th is is one

com ponent [ Team LiB ]of t he API , an d f or m ost p rog ram m ers, t he m ost f requ en t ly used p ack age dur ing dev elop ment . The API f or DBMS_ OUTPUT is list ed in Sect ion 9. 6 . The f ollow in g illust r at es t he SYS st at ement s ex ecu t ed, du r in g dat abase cr eat ion , t hat m ake DBMS_ OUTPUT available f or gener al use.

1.GRANT EXECUTE ON DBMS_OUTPUT TO PUBLIC; 2.CREATE PUBLIC SYNONYM DBMS_OUTPUT FOR SYS.DBMS_OUTPUT;

The f ir st st at ement m ean s t hat SCOTT and all f ut ur e Oracle account s can w r it e PL/ SQL t h at use t h e DBMS_OUTPUT p ack age. Th e k ey w or d PUBLI C giv es t he gr an t t o all users. Th e •second st at em Table en tofmContent eans tsh at SCOTT can w rit e PL/ SQL w it h st at em ent s lik e: Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

DBMS_OUTPUT.PUT_LINE('Hello'); Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 8 Wit houPages: t t h e44 second st at em en t , SCOTT w ould code t he follow in g:

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d SYS.DBMS_OUTPUT.PUT_LINE('Hello'); t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Figur e ag 9- 1e illust at esfeat t heurenescap su lat ofgers packand ages in t heprSYS t . u r es t hat allow y our adv ant of Orracle such asion t rig st ored ocedaccoun ur es- f eat dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es.r e Topics erfe edrinclude: Figu 9 - 1 .cov Re e nci ng t h e Or acl e PL/ SQL Pack a ge s. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] When SCOTT comp iles a pr oced ur e, Or acle ident if ies all r ef er enced ob ject s. I f t he SCOTT pr oced ur e r ef erences t he DBMS_OUTPUT p ack age, Or acle det erm ines t h at D BMS_OUTPUT is a sy non ym f or SYS. DBMS_ OUTPUT and t hat SCOTT has EXECUTE p r iv ileg es on t hat p ack age.

[ Team LiB ]

9.2.2 The API How ex t en siv e is t h e API ? I t in clud es hun dr ed s of pack ages. Most pack ages begin w it h DBMS. Som e ut ilit y pack ages begin w it h UTL such as UTL_SMTP—a PL/ SQL API in t erf ace t o t h e SMTP ser v ice. To p r ev iew all pack ages in t he API t h at b eg in w it h DBMS or UTL, q uery t he dat a dict ionar y v iew ALL_ OBJECTS. The f ollow ing SQL g en er at es a spool file list in g t he DBMS and UTL pack ages. This script r uns w it h TERM off , w hich t u r ns t er min al- out pu t of f. Th e scr ipt dir ect s out p ut st rict ly t o t he spool file, ALL_ OBJECTS. LST.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

-Filename ALL_OBJECTS.SQL By Kevin Owens set pagesize 0 set term off setPub feedback off lish er: Prent ice Hall PTR spool all_objects Pub Dat e: Decem ber 0 5, 2 003 SELECT object_name I SBN: 0- 13 -0 850 33 -0 FROM all_objects 44 8 WHEREPages: owner='SYS' AND object_type='PACKAGE' AND (object_name like 'DBMS%' OR object_name like 'UTL%'); set feedback on Ef fectterm ively on creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t set Kevin ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d spool Ow off t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using o- follow inst r uct ions d ex am ples, t his book esentes. s t echniq ues ting o t ake The oueasyt pu t ftile ALL_OBJECTS. LSTan w ill include h und reds of pr packag Th e follow illu st r at es adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat allow y our t he t ex t of t he list f ile generat ed: dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y SQL> @ALL_OBJECTS plexa r ule t This Com shows fewenf oforcem the en hundreds of packages. DBMS_ALERT PL/ SQL p r ogr am un it s and langu age f eat u res DBMS_APPLICATION_INFO DBMS_AQ Dat a t y pes and comp osit e st r u ct u re DBMS_AQADM DBMS_AQADM_SYS Er r or han dling and except ions DBMS_AQADM_SYSCALLS DBMS_AQIN I nt er - pr ocess com mu nicat ions DBMS_AQJMS DBMS_AQ_EXP_HISTORY_TABLES Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr m ingAPI Oracle igger ed ePrar oced uree es ,appr Th iroaches d Ed it ion is an invtaluable esou As w itam h any , h owTrdo yous uand se itSt ? or Ther e t hr t o , lear ning h e API fror anrce for dat abase ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Or acle packagde. int ellig en t , com plex dat abases. YouLiB can [ Team ] u se t he SQL* Plus D escrib e comm and . This is a defin it ion of t h e int erf ace only . You can ex t r act t he p ackag e sou rce f r om t he d at a d ict ion ary . Th is fr equent ly includ es exam ples an d d et ailed descr ipt ions on u sing t h e API .

YouLiB can [ Team ] v isit t he fr ee Or acle W eb sit e, t echnet . or acle. com , t o r ev iew t he p ackag e docum ent at ion . You can d escr ib e a p ack age sp ecificat ion wit h t h e SQL* Plus DESCRI BE com m and . Ex am ples in t he t ex t u se t he DESCRI BE com m and f or t ables. This com m and also descr ibes v iew s pr oced ur es, fun ct ion s, and pack ages. The DESCRI BE com m and show s t h e int erf ace. This includes p rocedur e an d f un ct ion nam es w it h each par am et er t yp e, mod e, and defau lt opt ion . This is u sef ul if y ou are alr eady f amiliar w it h an API and need t o r eview t h e sp ecifics of t h e int er face.

SQL> DESC name-of-package-procedure-function •

Table of Content s

Pr ogrexam am m ing Tr i gger Stor et he d P roce s, Thir d Edi ti on For ple,Ortahclee ®follow ings and spools in t erdure f ace sp ecificat ion

for t h e DBMS_ OUTPUT packag e t oKevin a f ile, DBMS_OUTPUT_ SPEC. LST. The f ollow ing session out pu t show s a par t ial By Owens list in g—t h er e ar e m any ot h er pr oced ur es t o t h e DBMS_OUTPUT p ack age. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 SQL> spool dbms_output_spec SQL> desc dbms_output

PROCEDURE ENABLE Ef fect ively creat e an d man age w it hDefault? Or acle! Sy st ems and dat ab ase ex per t Argument Name Typecom plex dat abases In/Out Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er-----t o t h e St r uct ur ed Query Langu age ( SQL) , an d --------------------------------------t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. BUFFER_SIZE NUMBER(38) IN DEFAULT Using easy- tPUT_LINE o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake PROCEDURE adv ant ag e of acle feat ur Type es such as t rig gers In/Out and st ored pr oced ur es- f eat u r es t hat allow y our Argument Or Name Default? dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he ------------------ --------------- ------ -------bu sin ess evolv es. Topics cov er ed include: A VARCHAR2 IN SQL> spool off View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t The SQL* Plu s DESCRI BE ou t put of a p ack age is a t ab ulat ed st y le v iew of t he pack age specifPL/ icatSQL ion . pThis ayun n ot sulangu ff icient in for muat ion if y ou ar e lear nin g t o use t h is packag e for r ogrm am it sbe and age f eat res t he fir st t im e. I t is m erely a definit ion of t he int er f ace at a q uick glance. The p r eceding DESCRI pu and t show s p rocedu an d PUT_ LI NE, w hich hav e t his in t er f ace DatBE a tout y pes comp osit e stres r u ctENABLE u re defin it ion . Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch procedure m or e enable(buffer_size IN NUMBER); procedure PUT_LINE(A VARCHAR2); Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int , com dations abases. Youellig canendt escr ib plex e fu nct an d pr ocedu res as well. Ref er t o Sect ion 9. 1 , " D BMS_OUTPUT, " for addit ional infor m at ion on usin g DBMS_OUTPUT. [ Team LiB ] A second opt ion is t o p ull t h e pack age specif icat ion sour ce fr om t h e dat a dict ionar y w it h a qu er y ag ain st t he view ALL_SOURCE. The result is t he p ack age in t er f ace sp ecificat ion t hat fr equ en t ly inclu des comm ent s on h ow t o use t he API . Th e SQL t o perf or m t his is in clud ed in

Sect ion LiB 9. 6 ,] " USER_SOURCE." [ Team [ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

9.3 USER_OBJECTS The USER_OBJECTS v iew pr ov id es st at us inf or mat ion on obj ect s y ou creat e. This in clu des t ables seq uences, v iew s, st or ed pr ocedu res, dat abase lin ks, an d ot hers. Th e follow ing is a p ar t ial descr colum ns f rom t his v iew . Use t his view t o det er m ine if a st or ed pr oced ur e is valid, if you need t o or t o det erm ine it s last comp ile t im est am p. Refer t o Ch apt er 5 f or a com p let e d escr ip t ion of t he dif fer en ces bet w een t h e USER, ALL, an d D BA dict ionar y v iew s.



USER_OBJECTS pr ovsid es in for m at ion only on t hose obj ect s you hav e cr eat ed in you r accou Table of Content

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

ALL_OBJECTS p rov ides inf or mat ion on obj ect s y ou hav e cr eat ed plus ob ject s t o wh ich y ou pr iv ileges.

By Kevin Owens

DBA_OBJECTS pr ov id es in for m at ion on all object s in t he d at abase. You need t he Or acle r ol SELECT_ CATALOG_ROLE t o access DBA v iew s.

Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003

Becau se I SBN: t he0-scope 13 -0 850of 33 DBA -0 view s is ever yt hing in t he dat abase, you m ust h ave eit h er t he Or acle t he OrPages: acle SELECT_CATALOG_ROLE r ole. Th e DBA role h as high pr iv ileges. SELECT_ CATALOG_R 44 8 int end ed f or users w h o need t o q uery d at a d ict ion ary v iew s. Applicat ion d ev elopers sh ould b e gi r ole. A p r ocedu re y ou creat e w ill h ave an ent r y in USER_OBJECTS. I f BLAKE cr eat es a pr oced ur e HELL Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t and gr an t s execut e on t hat pr ocedur e t o you , t hen y ou can see t his obj ect w hen y ou qu er y OWN Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d OBJECT_NAME, and OBJECT_TYPE fr om ALL_ OBJECTS. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SQL> desc user_objects Name Null? Type --------------------------------------------------View in g const r aint s in t h e dat a dict ion ar y OBJECT_NAME VARCHAR2(128) OBJECT_TYPE VARCHAR2(18) Com plex r ule enf orcem en t CREATED DATE LAST_DDL_TIME PL/ SQL p r ogr am un it s and langu age f eat u resDATE STATUS VARCHAR2(7) a t y pes and comp osit e st r u ct u re And Dat other columns Er r or han dling and except ions These ar e t he colum ns relevan t t o obj ect nam e, t yp e, and st at us. Ther e ar e a f ew ot her colum ns I nt erD- profocess com OBJECT_I t he ob jectmu innicat t he ions d at abase. Relev ant t o t his discu ssion, t hese colu mn s hav e t he fo m ean ing. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] OBJECT_NAME

This is t he nam e in t he CREATE OR REPLACE clause. This is not t he host f ile. R scr ipt @MY_ HELLO. SQL w it h a CREATE OR REPLACE PROCEDURE HELLO st at e creat es t h e obj ect nam e HELLO. Th e dat a dict ionar y st ores all at t rib ut es in upp

OBJECT_TYPE

For PL/ SQL t his is FUNCTI ON, PROCEDURE, PACKAGE, or PACKAGE BODY. The an und er score in PACKAGE BODY.

CREATED

This is t he pr ogr am cr eat ion d at e. To see t he p recise t ime of cr eat ion, chan ge display f or a D ATE f or mat :

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON HH24:MI';

you d rop a pr ocedu re, r un ning t h e CREATE OR REPLACE scr ip t r eset s t he CR Table ofI fContent s



Thsisand is Stor eq uiv t o crs,eat ing t he object Pr ogr am m ing Or a cl e ®dat Tr e. i gger e d alent P roce dure Thir d Edi ti on By Kevin Owens

f or t he fir st t im e. Once cr eat ed, r ecom pile it man y t im es. Th e r ecom pile dat a is t he LAST_DD L_TI ME dat e.

LAST_DDL_TIME You can r ecom p ile a st or ed pr oced ur e m any t im es. The r ecom p ile m igh t f ail or succeed. Eit her w ay , t he r ecomp ilat ion up dat es t h e colu mn LAST_ DDL_TI ME. Pub lish er: Prent ice Hall PTR

STATUS

Ob ject s can h ave a st at us of VALI D or I NVALI D. A pr ocedur e t h at insert s int o t STUDENTS t able becomes inv alid if y ou dr op t he STUDENTS t able. All ob ject s 0- 13 -0 850 33 -0 VALI D.

Pub Dat e: Decem ber 0 5, 2 003 I SBN:

Pages: 44 8

The f ollow in g SQL is a gener al r epor t on all t h e PL/ SQL p rog ram unit s you hav e com piled int o y o Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. -- Filename CHECK_PLSQL_OBJECTS Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake column object_name format a20 adv ant ag e of Or acle feat ur es such t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our column last_ddl_time heading as last_ddl dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he SELECT object_name|| bu sin essdecode(object_type,'PROCEDURE','(P)', evolv es. Topics cov er ed include: 'FUNCTION','(F)', 'PACKAGE','(Spec)', 'PACKAGE BODY','(Body)') object_name, View in g const r aint s in t h e dat a dict ion ar y status, created, last_ddl_time FROM Com user_objects plex r ule enf orcem en t WHERE object_type in ('PROCEDURE', 'FUNCTION', PL/ 'PACKAGE','PACKAGE SQL p r ogr am un it s andBODY'); langu age f eat u res Dat a t y pes and comp osit e st r u ct u re This ou t put includes each p r ocedu re, f unct ion, sp ecificat ion and bod y, t he st at us, an d last com p t her e Er isr one pr ocedu re, HELLO, t he r esult is: or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e OBJECT_NAME STATUS CREATED LAST_DDL_TIME Pr ogr am m ing Oracle Tr igger----------------s and St or ed Pr oced ur----------------es , Th ir d Ed it ion , is an inv aluable r esou rce -------------------for dat abase d ev elopers, er s, and pr16:18 oj ect leader s look in g 16:18 t o b uild an d m aint ain t r uly HELLO(P) VALID d esign 14-jul-2003 14-jul-2003 int ellig en t , com plex dat abases. [The Team ] - in fun ct ion USER evaluat es t o y our cur r ent Oracle session accoun t . To see w hat pa SQLLiB built ot her u ser s hav e ex t en ded t o y ou, ex clu ding t he d at a d ict ion ary SYS pack ages, select all PACKA obj ect s fr om ALL_OBJECTS an d ex clu de SYS and you rself:

[ Team LiB ]

SELECT owner, object_name FROM all_objects WHERE object_type='PACKAGE' AND owner AND owner USER;

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

9.4 Dependencies among Procedures This sect ion cov er s t h e follow ing t opics: Ed it in g and com p iling a pr ocedu r e t hat inv alid at es ot her pr oced ur es. LAST_ DDL_ TI ME and STATUS fr om USER_ OBJECTS. Com piling a schem a w it h DBMS_ UTI LI TY. COMPI LE_SCHEMA. •

RecompTable ilin gofp Content r ocedusres, fu nct ions, and p ack ages ind iv idu ally .

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

This sect ion u ses t h e scr ipt CHECK_ PLSQL_OBJECTS f r om t he p r ev ious sect ion .

By Kevin Owens

When w e fir st com pile t he HELLO p rocedur e, t h e CREATED t ime and LAST_D DL_TI ME ar e ident ical. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

OBJECT_NAME STATUS CREATED LAST_DDL_TIME -------------- ------- ----------------- ----------------HELLO(P) VALID 14-jul-2003 16:18 14-jul-2003 16:18 Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tI eaches y ou npile eed t thoe kn t ourbuild ustcom an d com plext hdat aboced asesurf or f w e at t you empw t hat t o r ecom prow oced e androb t he pile f ails, e pr e isy our st ill binusiness. t he dat a dict ionar y bu t w it h an I NVALI D st at us. Th e LAST_D DL_ TI ME r eflect s t he last com pile Using t im e. easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases poreatt e buis siness r ules t oacle manerage Ex ecu t ing at op incor rocedur h at I NVALI D wwillhich fail ar w ite heasy an Or r or:and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PLS-00905: object SCOTT.HELLO is invalid PL/ SQL p r ogr am un it s and langu age f eat u res I f Procedu A calls ocedur e eBstand b ecom es in valid, t hen A aut omat ically becomes Dat a re t y pes andPrcomp osit r u ctBu re inv alid. For t he Figur e 9- 2 p r ocedu re, SAY_ HELLO calls HELLO. Wh at h appens if HELLO becom valid? Eres r orinhan dling and except ions I nt er - pr ocessFigu com mu r e nicat 9 - 2ions . Si m ple

Pr oce dur e D ep en de ncy .

Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

We Pub b egDat in e:w it h t he t o HELLO. SQL an d SAY_ HELLO. SQL. Decem bercod 0 5, e2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

-- Filename HELLO.SQL Ef fect ively e an d PROCEDURE man age comhello plex dat CREATE ORcreat REPLACE ISabases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin BEGIN Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. dbms_output.put_line('Hello'); END; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake / adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our show errors dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu ess evolv SAY_HELLO.SQL es. Topics cov er ed include: -- sin Filename CREATE OR REPLACE PROCEDURE say_hello IS BEGIN View in g const r aint s in t h e dat a dict ion ar y hello; END; Com plex r ule enf orcem en t / show PL/ errors SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Com pile p rocedur es HELLO and SAY_HELLO in or der . The SHOW ERRORS com m and repor t s any com pilat iondling er r orand s. The scrip t CHECK_PLSQL_OBJECTS show s t he STATUS as VALI D f or Er r or han except ions each p rocedur e in USER_OBJECTS. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce SQL> @CHECK_PLSQL_OBJECTS for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. OBJECT_NAME STATUS CREATED LAST_DDL_TIM -------------------- ------- ------------ -----------[HELLO(P) Team LiB ] VALID 25-jul 12:52 25-jul 01:02 SAY_HELLO(P) VALID 25-jul 01:01 25-jul 01:02

Ed it HELLO. [ Team LiB ]SQL and chan ge PUT_LI NE t o PUTLI NE. The pr ocedur e w ill now com p ile w it h an err or . Recom pile HELLO wit h @HELLO.SQL. The st at us of SAY_HELLO is also inv alid, y et w e did not chang e t he p rocedur e. SAY_HELLO depend s on a v alid HELLO pr ocedur e. A com pile err or in Hello r esult ed in Oracle searching ob ject s t hat depend on HELLO an d in validat in g t hose ob ject s. All dependent s of any pr ocedur e m ust be v alid f or t hat pr ocedur e t o be v alid, show ing bot h obj ect s as inv alid :

SQL> @CHECK_PLSQL_OBJECTS OBJECT_NAME STATUS -------------------- ------HELLO(P) INVALID • Table of Content s SAY_HELLO(P) INVALID

CREATED -----------25-jul 12:52 25-jul 01:01

LAST_DDL_TIM -----------25-jul 01:05 25-jul 01:02

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Cor r ect t he PL/ SQL code in HELLO. SQL and r ecom pile. The HELLO should be v alid wit h a successful recom pilat ion. Wh at ab out SAY_ HELLO, is t h is st ill in valid? Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

SQL> @hello Procedure created. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d SQL> @CHECK_PLSQL_OBJECTS t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. OBJECT_NAME STATUS CREATED LAST_DDL_TIM Using easy- t o- follow inst r------uct ions an-----------d ex am ples, t his book pr esent s t echniq ues t o t ake ------------------------------adv ant ag e of Or acle feat ur es such as t rig gers and st ored oced ur es- f eat u r es t hat allow y our HELLO(P) VALID 25-jul 12:52 25-julpr01:17 dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he SAY_HELLO(P) INVALID 25-jul 01:01 25-jul 01:02 bu sin ess evolv es. Topics cov er ed include: Pr ocedu r e SAY_HELLO is st ill in valid; how ever , w hen w e execut e t h e pr oced ur e, Or acle sees View in g const r aint s in t h e dat a dict ion ar y t hat it is in valid and at t em pt s t o v alid at e it . This w ill b e successf ul becau se all dependent s ( i. e. , Com t he HELLO pr oced ur e) ar plex r ule enf orcem enet valid. Or acle com piles SAY_HELLO, set s t h e st at us t o v alid , and t h en execut es t h e pr oced ur e. Follow ing ex ecut ion of HELLO, bot h p rocedur es ar e v alid . PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SQL> execute say_hello HelloI nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch PL/SQL procedure successfully completed. m or e SQL> @CHECK_PLSQL_OBJECTS Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, STATUS d esign er s,CREATED and pr oj ect leader s look in g t o b uild an d m aint ain t r uly OBJECT_NAME LAST_DDL_TIM int ellig en t , com plex dat abases. -------------------- ------- ------------ -----------HELLO(P) [SAY_HELLO(P) Team LiB ]

VALID VALID

25-jul 12:52 25-jul 01:17 25-jul 01:01 25-jul 01:17

Ther e is un derst an dable ov erh ead w it h Or acle at t em pt in g t o v alidat e obj ect s at r un t im e. I f

HELLO aw [ Team isLiB ] idely used p r ocedu re an d becom es inv alid, t h er e w ill be som e p er for m ance degr adat ion . Du ring t h e nor m al oper at ions of an app licat ion, Or acle m ay encoun t er m any pack ages t hat became in valid and r ecom pile t h em at r un t im e. This can cau se a not iceable im pact t o end user s. The f ollow in g d iscussion cov ers t he scen ario w hen inv alid cod e does not r ecom pile. We inv alidat ed HELLO, r ecom piled it , and it b ecam e v alid ag ain . The ch ange w as a sim p le st at ement chang e t hat w e corr ect ed . A m aj or code chan ge t o HELLO could cause r ecom pilat ion failur es in ot her pr oced ur es. Su ch an event w ould occu r if t he int er face t o HELLO ch anged. Chan ging t he p ar amet er specif icat ion , par am et er t yp es, or par amet er m odes can perm anent ly in validat e ot her code. I f w e ch ange a pr ocedur e and r ecom p ile, Or acle' s r ecom pilat ion of ot her pr ocedur es m ay fail. Why wait un t il r un- t im e t o r ealize t h er e is b rok en cod e. W hen PL/ SQL chang es occur , y ou can r ecom pile t h e en t ire su it e of PL/ SQL code in t he schem a. The Or acle D BMS_UTI LI TY pack age •pr ov ides t hisTable Content f unctofionalit y sw it h t he COMPI LE_SCHAME p rocedur e. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

To r ecomp ile all PL/ SQL in a schem a ( t h is ex am ple uses t he schem a n ame, SCOTT) : By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 SQL> execute dbms_utility.compile_schema('SCOTT') Pages: 44 8

PL/SQL procedure successfully completed.

The r esponse " perocedur e successfu lly com ed" means he callSyt st o ems DBMS_UTI LIab TYase w asex per t Ef fect ively creat an d man age com plex datplet abases w it h Ort acle! and dat successful. There m ay b e SQL, inv alidOrob ject s.answ RunerCHECK_PLSQL_OBJECTS inv alid or ed, an d Kevin Ow ens ex plor es PL/ acle's t o t h e St r uct ur ed Query for Langu age st ( SQL) pr oced uryou es. LAST_DD r ecom pilat e of each t eaches w hat y ou L_TI n eedME t o show kn ows t oh ebuild rob ust ion an dt im com plex datpr abocedu ases re. f or y our b usiness. IUsing f a p rocedur e follow is inv alid, ou ions can an SHOW ERRORS on tbook hat prproced urse,t echniq sh ow inues g wh f ailed t o easy- t oinst ryuct d ex am ples, t his esent t oyt it ake com pileagweitof h tOr h eacle follow ing: adv ant feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SHOW ERRORS . SHOW procedure_name; View inERRORS g const r PROCEDURE aint s in t h e dat a dict ion ar y SHOW ERRORS FUNCTION Com plex r ule enf orcem enfunction_name; t SHOW ERRORS PACKAGE package_name; spec errors) PL/ SQL p r ogr am un it s and langu age f eat(package u res SHOW (package body errors) Dat a tERRORS y pes andPACKAGE comp ositBODY e st r upackage_name; ct u re To sh Er owr or comp hanile dling er r or and s for except SAY_ ions HELLO: I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e SHOW ERRORS PROCEDURE SAY_HELLO; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int en t ,incom plex dat abases. t h ree p rocedur es. P1 calls P2 , w hich calls P3. The pr ocedur e Theellig f ollow g scenar io includes code is: [ Team LiB ]

CREATE OR ]REPLACE procedure P3 IS [ Team LiB BEGIN dbms_output.put_line('executing p3'); END; / CREATE OR REPLACE procedure P2 IS BEGIN P3; END; / CREATE OR REPLACE procedure P1 IS BEGIN P2; END; / •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Com pile t h ese p rocedur es in t he f ollow ing or der : P3 , t hen P2, t hen P1 . Ex ecu t ion of P1 By Kevin Owens pr odu ces t h e follow ing: Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

SQL> execute Pages: 44 8 p1 executing p3

Ch ange P3 creat b y adding parage am et er tplex o t hedat inabases t erf ace w and p ile Sy t hestpr ocedur Ef fect ively e an d aman com it h com Or acle! ems and e. dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CREATE OR REPLACE procedure P3(N INTEGER) IS dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he BEGIN bu sin ess evolv es. Topics cov er ed include: dbms_output.put_line('executing p3'); END; / View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t Not kn owin g all t he depend en cies on P3, we can com pile t he schem a. PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SQL> execute dbms_utility.compile_schema('SCOTT'); I nt er - pr ocess com mu nicat ions PL/SQL procedure successfully completed. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Ch eck f or inv alid ob ject s. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] SQL> @check_plsql_objects OBJECT_NAME

STATUS

CREATED

last_ddl

-------------------[ Team LiB ] P1(P) P2(P) P3(P)

------INVALID INVALID VALID

-----------25-jul 15:26 25-jul 15:26 25-jul 15:26

-----------25-jul 15:35 25-jul 15:35 25-jul 15:35

We h ave in valid obj ect s P1 and P2 . Use SHOW ERRORS t o see w hy t h ese p rocedur es f ailed t o com pile.

SQL> show errors procedure p1 Errors for PROCEDURE P1: •LINE/COL ERROR Table of Content s Pr ogr am m ing---------------------------------------------------Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on --------

3/5 PLS-00905: object SCOTT.P2 is invalid By Kevin Owens 3/5 PL/SQL: Statement ignored SQL> Pubshow lish er: Prent errors ice Hallprocedure PTR p2 Errors for PROCEDURE P2: Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

LINE/COL ERROR Pages: 44 8 -------- ----------------------------------------------------3/5 PLS-00306: wrong number or types of arguments in call to 'P3' 3/5 PL/SQL: Statement ignored Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tMan eaches hatecty soucan n eed t o aknch owalleng t o build rob ust an Idn com dat ab f orley(our usiness. y invyou alid wobj pose ing pr oblem. t h e plex pr ecedin g ases ex amp P1, bP2 an d P3) , t her e are t w o inv alid ob ject s. We chang ed P3 and saw f rom SHOW ERRORS t h at P2 is Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake passing t he w r ong nu m ber of arg um ent s t o P3. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat t o incor por at e buLE_SCHEMA siness r ules com w hich ar ealleasy o man y as can t he validat e Theab D ases BMS_UTI LI TY.COMPI piles t he tPL/ SQLage in aand sch m emodif a. You bu sin ess evolv es. Topics cov er ed include: indiv idual comp onent s w it h t he ALTER st at ement . View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t ALTERPL/PROCEDURE procedure_name SQL p r ogr am un it s and languCOMPILE; age f eat u res ALTERDat FUNCTION function_name a t y pes and comp osit e st r uCOMPILE ct u re Er r or han dling and except ions To com pile t h e packag e specif icat ion and bod y: I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr amPACKAGE m ing Oracle Tr igger s andCOMPILE; St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce ALTER package_name for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. To com pile j ust t h e pack age specif icat ion : [ Team LiB ]

[ Team PACKAGE ALTER LiB ] package_name COMPILE SPECIFICATION;

To com pile j ust t h e pack age bod y:

ALTER PACKAGE package_name COMPILE BODY;

You can alw ay s det erm ine object d ep en dencies b y qu er y ing t he d at a d ict ionar y v iew USER_D EPEND ENCI ES, cov er ed in t h e nex t sect ion . The p receding scenar io includ es t hr ee pr oced ur es: P1, P2 , and P3. This is not a com plex ar chit ect u re. W hen t h er e ar e m any pr ogr am u nitTable s w itofh Content m any depend en cies, t he t ask becom es t edious. I t requ ires r epeat ed • s qu er ies of t he USER_DEPENDENCI ES v iew . I n t he n ex t sect ion, w e look at app lying a general Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on solut ion t o q uery ing USER_D EPENDENCI ES. By Kevin Owens

The scr ipt u sed t o quer y t he USER_OBJECTS v iew , CHECK_ PLSQL_OBJECTS, filt er s st or ed pr oced ur es w it h a WHERE clause. This scrip t f ilt er s st or ed p rocedur es ju st t o demon st rat e an Pubple. lish er: ice Hall exam A Prent ch ange t oPTR a st or ed pr oced ur e can inv alidat e ot her obj ect t yp es. A view can use a Pub Dat e: Decem ber 0 2 003 PL/ SQL f un ct ion . A t r5, igg er can use a pr oced ur e, fun ct ion , or p ack age. Object s f rom ot her sch em as m ay u-0 se850 our PL/ SQL object s. A g en er al d ep en dency t r acin g st r at egy r equ ir es t hat I SBN: 0- 13 33 -0 y ou q uer y t he Pages: 44 8 ALL_D EPENDENCI ES v iew for all obj ect t yp es. [ Team LiB ] Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

9.5 USER_DEPENDENCIES The v iew USER_ DEPEND ENCI ES sh ow s all depend en cies for object s includ in g pr ocedu res, fu nct ions, pack age specificat ions, and pack age b odies. Query t his v iew t o see all PL/ SQL pr oced ur es t hat ar e dependent on a t ab le you ar e abou t t o dr op. The descript ion is:

SQL> desc user_dependencies • Name Table of Content s Null? Type Pr-----------------------------ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on ---------------------NAME NOT NULL VARCHAR2(30) By Kevin Owens TYPE VARCHAR2(12) REFERENCED_OWNER VARCHAR2(30) REFERENCED_NAME VARCHAR2(64) Pub lish er: Prent ice Hall PTR REFERENCED_TYPE VARCHAR2(12) Pub Dat e: Decem ber 0 5, 2 003 REFERENCED_LINK_NAME VARCHAR2(128) I SBN: 0- 13 -0 850 33 -0 SCHEMAID NUMBER Pages: 44 8 DEPENDENCY_TYPE VARCHAR2(4)

I f you w r it e a p r ocedu re, HELLO, t hat inser t s a r ow in t he STUDENTS t able, t her e w ill be a fect man age com plex abases w it h NAME= Or acle!STUDENTS. Sy st ems and dat ab ase ex per t rEfow inively t his creat v iew ewan it hdNAME= HELLO an d dat REFERENCED_ Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. NAME The n am e of t he p rocedur e f unct ion or p ack age t hat h as Using easy- t o- follow inst r uct an d tex t his book pr esent This s t echniq t o tju ake r efions erences o am t he ples, REFERENCED_NAME. v iewues is not st f or adv ant ag e of Or acle feat urst esorsuch as t rig gers and st ored pr oced ur esf eat u r es t hat allow y our ed pr ocedur es. View s an d ot h er object s h ave d ep en dencies as dat ab ases t o incor por at e bu r ules w hich ar e easy t o man age and m odif y as t he w siness ell. bu sin ess evolv es. Topics cov er ed include: TYPE For PL/ SQL p rog r am unit s, t his includes PROCED URE, FUNCTI ON, PACKAGE, and PACKAGE BODY. View in g const r aint s in t h e dat a dict ion ar y REFERENCED_OWNER This schem a ow ns t he r eferenced object . A pr ocedu r e can inser t a r ow Com plex r ule enf orcem en int t o a STUDENTS t able in anot h er schem a. The pr ocedu re is depend en t on t hat STUDENTS t able. This colum n is t he ow ner of PL/ SQL p r ogr am un it st he and langu age tfab eatle. u res STUDENTS REFERENCED_NAME Dat a t y pes and comp This osit eissttrhe u ctobj u reect nam e being r ef erenced. Th is can b e a t ab le, v iew , sequence, or d at abase link . This colum n w ill in clu de all ot h er pr oced ur es, fun ct ion s, and pack ages being ref er ences, in clud ing Er r or han dling and except ions pack ages in t he dat a dict ionar y such as DBMS_ OUTPUT. I nt er - pr ocess com mu nicat ions REFERENCED_LINK_NAME This is t he nam e of a dat abase link . A pr oced ur e could select fr om at a r pem otar e ysitkeeyw, ituhnique, t he syf nt t able_nam e@lin k_m nam Declar at iv e const r aintas,t able including rim orax eign k ey, ch eck , and uche. This w ou ld includ e t he link n am e. m or e SCHEMAID This is t he sch em a I D of t h e r ef er enced ow n er . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, dThis esigniserHARD s, andupr oj ectt hleader s look b uild m aint t r uly , DEPENDENCY_TYPE nless e depend en in cygist ot hr oughanadREF t ypain e object int ellig en t , com plex dat abases. t hen t his colum n v alu e is REF. [ Team LiB ] When a p rocedu re is in valid, t he t ask is t o ident ify all obj ect s t h at REFERENCE t hat pr oced ur e. To d o t h is, SELECT NAME, TYPE WHERE REFERENCED_NAME = t he inv alid ob ject . Con t inue t h is sear ch unt il t here ar e n o m or e depend en cies.

Ther e arLiB e a ]v ar iet y of way s t o aut om at e t his sear ch. Wr it ing a recur siv e PL/ SQL fu nct ion is [ Team one op t ion. Th e follow ing is one solut ion t hat pop ulat es a TEMP t ab le w it h a SELECT fr om USER_D EPEND ENCI ES. To dem onst r at e a scen ar io, con sid er t he im pact t o pr oced ur es P1 t hr ou gh P4, or an y ot her p rocedur es, w hen P5 b ecom es inv alid . This d ep en dency is illu st r at ed in Figur e 9- 3 . Th e pr oced ur e code for P1 t hr ough P5 is:

CREATE OR REPLACE procedure P5 IS BEGIN dbms_output.put_line('executing p5'); END; / CREATE OR REPLACE procedure P4 IS • Table of Content s BEGIN Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on P5; By Kevin Owens END; / CREATE OR REPLACE procedure P3 IS Pub lish er: Prent ice Hall PTR BEGIN Pub P4; Dat e: Decem ber 0 5, 2 003 END; I SBN: 0- 13 -0 850 33 -0 / Pages: 44 8 CREATE OR REPLACE procedure P2 IS BEGIN P5; END; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t / Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d CREATE OR REPLACE procedure P1 IS t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. BEGIN UsingP2; easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake P3; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our END; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he / bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e rdat y li d Figu e a9 dict - 3 .ion I narva

Pr oce du r es.

Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Assu m e for t he exam ple t hat all pr ocedu r es ar e in valid and w e need t o analy ze w hat calls P5 . What calls creat t he code calls t race dependency creat eSyastTEMP t abledat w ab it hase PARENT, Ef fect ively e an tdhat man ageP5? comTo plex dat aabases w it h Or, acle! ems and ex per t CHI LDOw colum Kevin ens ns. ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he CREATE temp (parent VARCHAR2(30), child VARCHAR2(30)); bu sin essTABLE evolv es. Topics cov er ed include: g const r aint, swin t h ecan datbaedict ar y in t h e t r ee. We st ar t w it h P5 . Load View t h e stinart in g p oint h ich anyion p oint Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res DatINTO a t y pes and VALUES comp osit('P5', e st r u ctnull); u re INSERT temp Er r or han dling and except ions Repeat t he f ollow ing I NSERT st at ement un t il t he m essag e 0 row s cr eat ed is r eceiv ed . I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce INSERT INTO temp for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly SELECT u.name a, t.parent b int ellig en t , com plex dat abases. FROM user_dependencies u, temp t WHERE u.referenced_name=t.parent [ Team LiB ] AND NOT EXISTS (SELECT * FROM temp WHERE parent=u.name AND child=t.parent);

[ Team LiB ] Select f r om TEMP, show n next , t o show t hat P1 calls P2 and P3, P2 calls P5, and so for t h .

PARENT -------------------P1 P1 P3 P2 P4 P5 •

CHILD ------P2 P3 P4 P5 P5

Table of Content s

Pr am Or a cl e ® eTrshould i gger s and dure s, Thir d Edi ti onile t he schema using Trogr acin gmining valid cod st arStor t weitd hP roce an at t emp t to comp DBMS_ UTI LI TY, d escr ib ed in Sect ion 9. 4 , " D ep en dencies am ong Pr oced ur es. " Aft er com pilin g By Kevin Owens t he schem a, t r ace inv alid ob ject s by ident if yin g t hose obj ect s t h at h ave an im m ed iat e depend en cy . For t h is ex am ple, ident if y pr oced ur es P4 an d P2 , because t hey d ir ect ly call pr oced ur er: e P5. Pub lish Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

Tr oubleshoot ing a dependency issu e is only r equir ed w h en code is chan ged an d recomp iled I SBN: 0- 13 -0 850 33 -0 w it hout any pr elim inar y analy sis. Th er e ar e nu m er ous met hod s for t r acing code d ep en dency. Pages: 44 8 The USER_DEPENDENCI ES v iew pr ovid es all necessar y inf or m at ion . You can au t om at e a pr ocess w it h a PL/ SQL solut ion or seq uent ially quer y t he USER_DEPENDENCI ES un t il y ou ident if y w here t he code is b rok en. How ex ter act sour code f ordat P4abases and P2? ay be y t odat inv igat Ef fectcan ivelyyou creat an dt he man agececom plex w itThis h Orm acle! Synecessar st ems and abest ase exeper t w hy t hOw e code is plor b rokes en. Use t heOrvacle's iews USER an dt oALL_SOURCE cov ered in t he age nex t( sect . d Kevin ens ex PL/ SQL, answ er t h e St r uct ur ed Query Langu SQL)ion , an t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. [ Team LiB ] Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

9.6 USER_SOURCE The sou rce code f or com piled pr ocedur es, fun ct ion s, packag es, or packag e bod ies is accessib le fr om t h e USER_SOURCE v iew . Refer t o Ch apt er 5 f or a det ailed exp lain at ion on t h e diff erences am ong dat a dict ionar y v iew s t hat hav e p refix es: USER, ALL, an d D BA. The PL/ SQL code y ou com pile in y our schema can be select ed at an y t im e fr om USER_ SOURCE. Qu er y USER_ SOURCE for t he PL/ SQL cod e you h ave com piled in y ou accoun t . •

Table of Content s

Qumering y ALL_SOURCE USER_SOURCE Pr ogr am Or a cl e ® Tr i gger sf or andever Storyetdhing P rocein dure s, Thir d Edi ti on

p lu s all ot her PL/ SQL t o w h ich y ou

hav e been given t he EXECUTE pr ivilege.

By Kevin Owens

Qu er y DBA_ SOURCE is all t he PL/ SQL code in t he dat abase. Pubse lish er: ice Hall Becau t hePrent scope of PTR DBA view s is ever yt hing in t he dat abase, you m ust h ave eit h er t he Pub Dat e: Decem ber 003 Or acle DBA r ole or t0h5,e 2Or acle SELECT_CATALOG_ ROLE r ole. The D BA r ole has h ig h pr iv ileges. SELECT_CATALOG_ROLE is int end ed f or users wh o n eed t o q uery dat a I SBN: The 0- 13 -0 850 33 -0 dict ionar y v iew s. App licat ion dev eloper s should be given t his r ole. Pages: 44 8

The v iew USER_ OBJECT uses t he colum n nam es: Ef fectOBJECT_NAME ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. OBJECT_TYPE Using easyt o- follow inst r uct ions am ples, t his book t echniq uesonent t o t ake The v iew s USER_DEPENDENCI ES an andd ex USER_SOURCE r eferprt oesent t he ssam e comp s w it h a adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat allow y our dif fer en t nam e: dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: NAME View in g const r aint s in t h e dat a dict ion ar y TYPE You can Com alw plex ay sr ule r et renf ieve orcem st or ed en tpr ocedu r e cod e fr om t his v iew . A pr oced ur e r ecr eat ed and com piled w it h er r or s is r et r ievab le fr om t h is view . PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SQL> desc user_source NameI nt er - pr ocess com mu nicat ions Null? Type ------------------------------ -------- --------------Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch NAME VARCHAR2(30) m or e TYPE VARCHAR2(12) LINE NUMBER Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce TEXT VARCHAR2(4000) for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. The colum [ Team LiBns] in t h e USER_SOURCE view hav e t h e follow ing descr ipt ion .

[ Team LiB ] NAME This is t he nam e in t he CREATE OR REPLACE clause. This is not t he host f ile. Runn in g t he scr ipt @MY_HELLO. SQL w it h a CREATE OR REPLACE PROCEDURE HELLO st at ement cr eat es t h e obj ect nam e HELLO. Th e dat a dict ionar y st ores all at t rib ut es in up per case. TYPE This is FUNCTI ON, PROCEDURE, PACKAGE, or PACKAGE BODY. Ther e is nev er an un derscor e in PACKAGE BODY. LINE This id en t if ies a line of t ex t . A 50- line t ex t file comp iled as a st or ed pr ocedu r e is 50 lines of t ext in t he dat a dict ionar y . Or acle does not r ef orm at t he t ex t . I f t h e pr ogr am fails at r un t im e, a line n um ber w ill be includ ed in t he er r or m essage. This shou ld b e m at ched w it h t h e LI NE num ber in t his v iew. I t is alw ays possib le t o ident if y t he specif ic lin e w it hin a st or ed p rocedur e at w hich ex ecu t ion f ailed . TEXT This is a line of t ext as r ead fr om t he orig in al sour ce file. •

Table of Content s

The ex m t ing of aOrPL/ SQL r ogrs am ave dailab ledure t hr ough is tiview Pr ogrtam a cl e ® Tr p i gger and is Stor P roce s, Thir dt hEdi on . You can q uer y USER_SOURCE and r edirect t he code t ex t t o a SQL* Plus sp ool f ile. I f t he or igin al sour ce cod e is lost , you can By Kevin Owens r ed irect t h e t ext t o a spool f ile w it h a SQL ext ension. The f ollow ing SQL script qu er ies t he sour ce for t he HELLO pr ocedu r e sp oolin g it t o a SQL f ile n am ed MY_ HELLO. SQL. Th e SQL* Plus com m and SET TERM su ppr esses out put for t he scrip t w hile t h e sou r ce HELLO is Pub lish er: Prent ice Hall PTR spooled t o t he SQL file. Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

-- Filename generate_my_hello.sql set Ef fectfeedback ively creatoff e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t set pagesize Kevin Ow ens ex0 plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d set term t eaches youoff w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. spool my_hello.sql SELECT '--t oFilename FROM Using easyfollow instMY_HELLO.SQL' r uct ions an d ex am ples,dual; t his book pr esent s t echniq ues t o t ake SELECT OR feat REPLACE ' FROM dual; adv ant ag'CREATE e of Or acle ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SELECT text FROMporuser_source dat ab ases t o incor at e bu siness r ules w hich ar e easy t o man age and m odif y as t he WHERE name='HELLO'; bu sin ess evolv es. Topics cov er ed include: SELECT '/' FROM DUAL; spool off View inon g const r aint s in t h e dat a dict ion ar y set term set feedback on Com plex r ule enf orcem en t set pagesize 1000 PL/ SQL p r ogr am un it s and langu age f eat u res Ru nning t h is scr ipt generat es a file MY_ HELLO. SQL. You can edit an d r ecomp ile t he HELLO Dat a t y pes and comp osit e st r u ct u re pr oced ur e using t his out pu t f ile. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch SQL> m@generate_my_hello.sql or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Thisdat p rod ucesd ev t heelopers, f ollow ing t ex t er f ile, MY_HELLO. showinng next for abase d esign s, and pr oj ect SQL, leaderas s look t o b :uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] -- Filename MY_HELLO.SQL CREATE OR REPLACE

PROCEDURE [ Team LiB ]hello IS BEGIN dbms_output.put_line('Hello'); END; /

You select t he sp ecificat ion of an Oracle p ack age f r om ALL_SOURCE. The f ollowin g g en er at es a sp ool file DBMS_OUTPUT w it h t he pack age specif icat ion an d d ocu m en t at ion f or using t h is Or acle packag e.

set feedback off •set pagesize Table 0 of Content s Pr ogr am m ing Or a cl set term off e ® Tr i gger s and Stor e d spool dbms_output By Kevin Owens SELECT text FROM all_source WHERE name='DBMS_OUTPUT'; spool Pub lish off er: Prent ice Hall PTR setPub term Dat e:on Decem ber 0 5, 2 003 set feedback on I SBN: 0- 13 -0 850 33 -0 set pagesize 1000 Pages: 44 8

P roce dure s, Thir d Edi ti on

The ou t pu t f rom t his scrip t w ill be a t ext f ile, DBMS_OUTPUT. LST, sh ow n n ex t . Th is t ext , ext r act ed fr om ALL_SOURCE, is t h e packag e specif icat ion as com piled in t he d at abase. The Ef fect ively creat e es an tdhe man age com plex datface abases h Or Sy st ems follow ing illust rat clarit y of t he int er def inwitition anacle! d d ocum en t atand ion tdat hatab ase ex per t Kevin ens ex plor Orpack acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d accom Ow p anies man y es of tPL/ he SQL, Oracle ages. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topicsas cov er ed include: package dbms_output ------------- OVERVIEW View in g const r aint s in t h e dat a dict ion ar y --- Com These information in a buffer plex procedures r ule enf orcemaccumulate en t -- (via "put" and "put_line") so that it can be retrieved -- PL/out (via or "get_lines"). If this SQLlater p r ogr am un it"get_line" s and langu age f eat u res -- package is disabled then all calls to this package are -- Dat simply This these routines are only a t y pesignored. and comp osit e st rway, u ct u re -- active when the client is one that is able to deal -- Er with r or han the dling information. and except ionsThis is good for debugging, or -- SP's that want to display messages or reports er -sql*dba pr ocess com nicat ions 'describing procedures', etc.). -- I ntto or mu plus (like -- The default buffer size is 20000 bytes. The at iv e is const r aintand s, including p rim ar is y k ey , u nique, f or eign k ey, ch eck , and m uch -- Declar minimum 2000 the maximum 1,000,000 m or e ------------ EXAMPLE Pr ogr -- am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for-dat abase d ev elopers, esign er and pr oj ect some leaderdebugging s look in g t o b uild an d m aint ain t r uly A trigger might d want tos, print out int-ellig en t , com plex dat abases. information. To do this the trigger would do -- dbms_output.put_line('I got here:'||:new.col||' is [ Team LiB ] -- the new value'); If the client had enabled the -- dbms_output package then this put_line would be -- buffered and the client could, after executing the -- statement (presumably some insert, delete or update

-- that [ Team LiB ] caused the trigger to fire) execute -begin dbms_output.get_line(:buffer, :status); end; -- to get the line of information back. It could then -- display the buffer on the screen. The client would -- repeat calls to get_line until status came back as -- non-zero. For better performance, the client would -- use calls to get_lines which can return an array of -- lines. --- SQL*DBA and SQL*PLUS, for instance, implement a -- 'SET SERVEROUTPUT ON' command so that they know -- whether to make calls to get_line(s) after issuing -- insert, update, delete or anonymous PL/SQL calls -- (these are the only ones that can cause triggers or -- stored procedures to be executed). -----------• Table of Content s -- SECURITY Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on -By Kevin -- Owens At the end of this script, a public synonym -- (dbms_output) is created and execute permission on -- this package is granted to public. Pub lish er: Prent ice Hall PTR ---------------------------Pub Dat e: Decem ber 0AND 5, 2 003 -PROCEDURES FUNCTIONS -- I SBN: 0- 13 -0 850 33 -0 procedure Pages: 44 8enable (buffer_size in integer default 20000); pragma restrict_references(enable,WNDS,RNDS); -- Enable calls to put, put_line, new_line, get_line -and get_lines. Calls to these procedures are -has dat notabases been w enabled. Ef fect ivelynoops creat eif an dthe manpackage age com plex it h Or acle! Sy st ems and dat ab ase ex per t -- Ow ens Set ex default amount information buffer. Kevin plor es PL/ SQL, Orof acle's answ er t o tto h e St r uct ur ed Query Langu age ( SQL) , an d -Cleanup data buffered from any dead sessions. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. -Multiple calls to enable are allowed. -- easyInput Using t o- parameters: follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake -adv ant ag ebuffer_size of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our of bytes, to buffer. dat-ab ases t oAmount incor por at einformation, bu siness r ules in w hich ar e easy t o man age and m odif y as t he -Varchar2, number and date items are stored in bu sin ess evolv es. Topics cov er ed include: -their internal representation. The information -is stored in the SGA. An error is raised if the const r aint s inist h e dat a dict ionIf ar y there are multiple -- View in gbuffer size exceeded. -calls to enable, then the buffer_size is generally r ule enf orcem t -- Com plex the largest ofenthe values specified, and will -always be >= than the smallest value p r ogr am un itCurrently s and languaage f eataccurate u res -- PL/ SQLspecified. more determination -is not possible. The maximum size is 1,000,000, pes and comp is osit e2000. st r u ct u re -- Dat a t ythe minimum procedure disable; Er r or han dling and except ions pragma restrict_references(disable,WNDS,RNDS); -- I ntDisable calls to nicat put,ions put_line, new_line, get_line er - pr ocess com mu -and get_lines. Also purge the buffer of any remaining -- Declar information. at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch procedure put(a varchar2); m or e pragma restrict_references(put,WNDS,RNDS); procedure put(a Tr number); Pr ogr am m ing Oracle igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce restrict_references(put,WNDS,RNDS); forpragma dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Put a piece ofabases. information in the buffer. int -ellig en t , com plex dat -When retrieved by get_line(s), the number and [ Team -LiB date ] items will be formated with to_char using -the default formats. If you want another format -then format it explicitly. -- Input parameters:

-a] [ Team LiB -Item to buffer procedure put_line(a varchar2); pragma restrict_references(put_line,WNDS,RNDS); procedure put_line(a number); pragma restrict_references(put_line,WNDS,RNDS); -- Put a piece of information in the buffer followed by -an end-of-line marker. When retrieved by get_line(s), -the number and date items will be formated with -to_char using the default formats. If you -want another format then format it explicitly. -get_line(s) return "lines" as delimited by "newlines". -So every call to put_line or new_line will generate a -line that will be returned by get_line(s). -- Input parameters: -a • Table of Content s -Item to buffer Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on -- Errors raised: By Kevin -- Owens -20000, ORU-10027: buffer overflow, limit of - bytes. --20000, ORU-10028: line length overflow, limit Pub lish er: ice bytes Hall PTR per line. -ofPrent 255 Pub Dat e: Decem ber 0 5, 2 003 procedure new_line; pragma I SBN:restrict_references(new_line,WNDS,RNDS); 0- 13 -0 850 33 -0 -- Pages: Put 44 an8 end-of-line marker. get_line(s) return "lines" -as delimited by "newlines". So every call to -put_line or new_line will generate a line that will -be returned by get_line(s). -Errors Ef fect ively creatraised: e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t -- Ow ens -20000, overflow, ofed Query Langu age ( SQL) , an d Kevin ex plorORU-10027: es PL/ SQL, Orbuffer acle's answ er t o t h elimit St r uct ur - bytes. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. --20000, ORU-10028: line length overflow, limit -- easyoft o255 bytes line. Using follow inst rper uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake procedure get_line(line outasvarchar2, status integer); adv ant ag e of Or acle feat ur es such t rig gers and st oredout pr oced ur es- f eat u r es t hat allow y our datpragma ab ases trestrict_references(get_line,WNDS,RNDS); o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he Get a single line back that has been buffered. bu -sin ess evolv es. Topics cov er ed include: -The lines are delimited by calls to put_line or -new_line. The line will be constructed taking all in g const r aint in t hae newline, dat a dict ion ar y -- Viewthe items ups to converting all the items -to varchar2, and concatenating them into a single plex r ule orcem en t fails to retrieve all lines before -- Com line. Ifenf the client -the next put, put_line or new_line, the non-retrieved p r ogr am un and langu age f eatis u resso if the client is -- PL/ SQL lines will beit sdiscarded. This -interrupted while selecting back the information, t y pes and st r u ctleft u re over which would -- Dat athere willcomp not osit bee junk -look like it was part of the NEXT set of lines. Er r or han dling and except ions -- Output parameters: -- I nt erline - pr ocess com mu nicat ions -This line will hold the line - it may be up to 255 -- Declar at bytes long. iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch -- m or estatus -This will be 0 upon successful completion of the -- am m ing call. means there more Pr ogr Oracle1 Tr igger sthat and St or ed Prare ocedno ur es , Th irlines. d Ed it ion , is an inv aluable r esou rce chararr is table of er varchar2(255) indexs look in g t o b uild an d m aint ain t r uly fortype dat abase d ev elopers, d esign s, and pr oj ect leader byenbinary_integer; int ellig t , com plex dat abases. procedure get_lines(lines out chararr, [ Team numlines LiB ] in out integer); pragma restrict_references(get_lines,WNDS,RNDS); -- Get multiple lines back that have been buffered. -The lines are delimited by calls to put_line or

-new_line. The line will be [ Team LiB ] -constructed taking all the items up to a newline, -converting all the items to varchar2, and -concatenating them into a single line. Once get_lines -is executed, the client should continue to retrieve -all lines because the next put, put_line or new_line -will first purge the buffer of leftover data. This is -so if the client is interrupted while selecting back -the information, there will not be junk left over. -- Input parameters: -numlines -This is the maximum number of lines that the -caller is prepared to accept. This procedure will -not return more than this number of lines. -- Output parameters: -lines • Table of Content s -This array will hold the lines - they may Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on -be up to 255 bytes long each. The array is indexed By Kevin -- Owensbeginning with 0 and increases sequentially. From a -3GL host program the array begins with whatever is -the convention for that language. Pub lish er: Prent ice Hall PTR -numlines Pub Dat e: Decem 0 5, 2 003 -Thisber will be the number of lines actually returned. -- I SBN: 0If 13 -0 it 850is 33 -0less than the value passed in, then there -- Pages: 44 are no more lines. 8 end;

[EfTeam LiBcreat ] fect ively e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

9.7 Sharing Code You creat e an Or acle accou nt w it h a user nam e, passw or d, and b asic r oles t hat allow t hat user t o cr eat e t ables an d p rocedur es. You add a n ew user nam ed BLAKE t o t he d at abase w it h t he follow ing :

CREATE USER BLAKE IDENTIFIED BY BLAKE •DEFAULT TABLESPACE Table of Content s STUDENT_DATA Pr ogr am m ing Or a cl e ® Tr i ggerTEMP; s and Stor e d P roce dure s, TEMPORARY TABLESPACE GRANT CONNECT, RESOURCE TO BLAKE; By Kevin Owens

Thir d Edi ti on

From hiser:p oin t ice f orHall warPTR d, BLAKE can cr eat e t ables and st or ed pr ocedur es. Anot her u ser SCOTT Pubtlish Prent is also cr eat in g p rocedur es. By defau lt , BLAKE cannot see SCOTT' S obj ect s and SCOTT can not Pub Dat e: Decem ber 0 5, 2 003 see BLAKE' S obj ect s. I SBN: 0- 13 -0 850 33 -0

Pages: 44 8ect s is done on a per- ob ject b ases. BLAKE can gr ant t able and pack age access Shar ing of obj t o SCOTT on an as- needed b asis. BLAKE h as a p ack age t hat pr ovid es select ed pay roll inf orm at ion. The PAYROLL pack age qu er ies dat a fr om a sen sit iv e SALARI ES t able. Th e SALARI ES t able is rest r ict ed. How ev er , BLAKE can select ively giv e access t o t he PAYROLL pack e of salar y abases inf or m at av acle! ailable hrems oug hand t hedat p rocedur es per andt Ef fectage. ivelyBLAKE creat econt an dr ols mant he aget yp com plex dat w ion it h Or Sytst ab ase ex fu nct ions h e defines in PL/ t heSQL, PAYROLL p ack age.erTot ogrt hant t heQuery r igh t tLangu o use age t he (PAYROLL Kevin Ow ens ex plor es Or acle's answ e StSCOTT r uct ur ed SQL) , an d pack age,you BLAKE t eaches w hatexecut y ou nes eedt hteo follow kn ow ing: t o build rob ust an d com plex dat ab ases f or y our b usiness.

Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SQL> GRANT EXECUTE ON PAYROLL TO SCOTT; View in g const r aint s in t h e dat a dict ion ar y SCOTT can n ow ex ecut e any pr oced ur e or f unct ion defin ed in t he PAYROLL pack age. SCOTT Com plex creat es a pr ivatr ule e syenf nonorcem ym : en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SQL> CREATE SYNONYM PAYROLL FOR BLAKE.PAYROLL; I nt er - pr ocess com mu nicat ions From Declar t his p oin war d, SCOTT can w r it PL/ ed pr ocedu res kt hey, at ch u se t he PAYROLL at ivt ef or const r aint s, including p erim arSQL y k eyst, or u nique, f or eign eck , and m uch pack age. SCOTT cannot access t he SALARI ES t able or an y ot her obj ect . Figur e 94 illust r at es m or e t his scenar io. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s,rand in g. t o b uild an d m aint ain t r uly Figu e 9 pr - 4oj. ect Shleader ar i ngs look Code int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

BLAKE can rev oke t he GRANT EXECUTE w it h t he follow in g: •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

SQL> EXECUTE PubREVOKE lish er: Prent ice Hall PTRON PAYROLL FROM SCOTT; Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

This im m ed iat ely in validat es t h e pr oced ur e in t he SCOTT account . I f SCOTT r un s t he PL/ SQL 44 8 pr ocedPages: ur e t hat uses t he PAYROLL p ack age, it w ill fail. I f BLAKE r eact iv at es t he g ran t , t hen Or acle w ill resolve t he inv alid p rocedur e. I t will r ecognize t h at SCOTT'S pr oced ur e is v alid and r un it . BLAKE can creat rev oke t he pr iv ilege fr om SCOTT; he can t h e pr ime. t im e tit Ef fect ively e an d man age com plex dat abases w itgrh an Ortacle! Syivilege st ems any and t dat abEach ase ex per w ill beOw r esolv Th er shou ld bOr e som e com w ur een SCOTT so t h ,atan d Kevin ens ed. ex plor esePL/ SQL, acle's answmerunicat t o t hion e Stbet r uct ed BLAKE Query and Langu age ( SQL) SCOTT PL/t oSQL codt e hen rob t hisust occu hisplex allev iatab esases Or acle om hav ing t o t eachescan your ecomp w hat yile ou tnhe eed kn ow ow build anrds—t com dat f or fyr our b usiness. r esolv e an in valid obj ect at r un t im e. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Iadv deally e ur becomes h e can anoced ALTER/ d or ant ,agif eSCOTT'S of Or aclecod feat es such inv as alid, t rig gers andexstecut orede pr ur es-COMPI f eat u rLE es com t hatman allow y our use DBMS_UTI LI TYpor t oatv e alidat e t he rcode. is cover ed inage Sect ionm9.odif 4 , y" Das epten dat ab ases t o incor bu siness ules wThis hicht op ar eiceasy t o man and hedencies am ong ocedues. res. " bu sin essPrevolv Topics cov er ed include: I f BLAKE w ant s t o shar e his code, h e mu st GRANT EXECUTE t o a u ser . BLAKE cann ot gr an t View in gileg const s in t h datgh a dict ion ar y execut e p riv es troaint SCOTT t herou a r ole. When Or acle com piles or r ev alidat es SCOTT'S pr oced ur es, it look s at t h e pr iv ileges in t he SCOTT account . I t does n ot look at r oles. The Com orcem en SCOTT'S t success orplex f ailurrule e ofenf com p iling cod e depends on SCOTT'S pr ivileges; r oles are ignor ed. The follow ing is a scenar io t hat exp lain s t his concept . PL/ SQL p r ogr am un it s and langu age f eat u res Con sider t he follow ing : Dat a t y pes and comp osit e st r u ct u re HR_ AD MI N is a senior r ole. HR is a less pr ivileged r ole. The f ollowin g cr eat es t he t w o roles. han dling except ions BecauEr ser or HR_ADMI N and is a senior r ole, all lesser roles ar e gr ant ed t o HR_ADMI N. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e SQL> CREATE ROLE HR_ADMIN; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce SQL> CREATE ROLE HR; for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly SQL> GRANT HR TO HR_ADMIN; int ellig en t , com plex dat abases. [ Team LiB ] The f ollow in g SQL cr eat es t he u ser SCOTT an d g ran t s f iv e r oles t o SCOTT. How ever , t he defau lt r oles for SCOTT ar e CONNECT and RESOURCE. W hen SCOTT conn ect s t o t he dat ab ase, h e only h as t he CONNECT and RESOURCE roles. SCOTT can enab le t he ot h er roles w it h a SET ROLE com m and .

[ Team LiB ]

SQL> CREATE USER SCOTT IDENTIFIED BY TIGER; SQL> GRANT CONNECT, RESOURCE, HR, HR_ADMIN TO SCOTT; SQL> ALTER USER SCOTT DEFAULT ROLE CONNECT, RESOURCE;

The f ollow in g scenar io supp oses t h at r oles ar e used w hen comp ilin g p rocedu res—t his is n ot t he case. This scen ar io is t o illust r at e w hy . Su ppose BLAKE g ran t s execut e on PAYROLL t o HR_ AD MI N. SCOTT connect s t o t he dat abase w it h d ef ault roles CONNECT, an d RESOURCE. When SCOTT connect s t o t he dat abase, t he p rocedur e t h at u ses t h e PAYROLL p ackag e is •inv alid. This Table of Content is becau se t hes HR_ ADMI N is not a default r ole and has n ot been set . SCOTT Pr ogr ames m ing a cl e m ® and Tr i gger and Stortehe d Prole. roce dure s, Thir d Edi ti on execut t h eOrcom t os en able By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

SQL> SET ROLE HR_ADMIN; I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

SCOTT has n ow enabled t he r ole t o w hich t h e pack age execut e p r iv ileg e w as giv en. This scenar io can be mor e com plicat ed . Applicat ion pr ogr am s set r oles, based on t he usern am e, t o en able v ariou s par t s of an app licat ion. Roles can be g r ant ed t o ot h er r oles. The d yn amics of r oles allow s r un - t ime ex age ecu t com ion of t hedat follow ing :w it h Or acle! Sy st ems and dat ab ase ex per t Ef fect ively creat e an d man plex abases Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SQL> SET tROLE HR_ADMIN, HR; r ules w hich ar e easy t o man age and m odif y as t he dat ab ases o incor por at e bu siness SQL> SETevolv ROLE bu sin ess es.HR; Topics cov er ed include: const s in tand h e dat a dict y ap plicat ion s, it is r eason able t h at user Giv enView t h e in dygnam icsr aint of roles t h eir u seion war it hin accou nt s b e t he b asis for p rocedur e g ran t s, as show n in Figur e 9- 4 . Com plex r ule enf orcem en t You cannot do t he f ollow ing : PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes CREATE ROLE andHR; comp osit e st r u ct u re Er r or han GRANT EXECUTE dling and ON except PAYROLL ions TO HR; I nt er - prHR GRANT ocess TO com SCOTT; mu nicat ions Declar iv e const rim ar yrek tey , uuses nique, f or eign k ey,age. ch eck , and m uch Ex pectatSCOTT t o rwaint r it es,a including PL/ SQL prpocedu hat BLAKE' S pack m or e BLAKE m ust Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] GRANT EXECUTE ON PAYROLL TO SCOTT;

[[ Team Team LiB LiB ]]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

9.8 Compilation Dependency Con cer ning j ust pack ages, a specificat ion m u st exist an d com pile w it hou t er ror s b ef or e t he pack age b ody can com pile.

9.8.1 Scenario 1 The f ollow in g is a pack age specif icat ion an d b ody . Ther e is one p r ocedu re. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

-- Filename PK_SPECIFICATION.SQL CREATE OR REPLACE PACKAGE pk is Pub lish er: Prent ice Hall PTR PROCEDURE p1; Dat e: Decem ber 0 5, 2 003 ENDPub pk; I SBN: 0- 13 -0 850 33 -0 / Pages: 44 8

-- Filename PK_BODY.SQL CREATE OR REPLACE PACKAGE BODY pk is PROCEDURE p1 IS begin Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t dbms_output.put_line('execute Kevin Ow ens ex plor es PL/ SQL, Or acle's answ erp1'); t o t h e St r uct ur ed Query Langu age ( SQL) , an d ENDyou p1;w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. t eaches END pk; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake / adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he Figur 9- 5evolv illust r atTopics es t he cov packag PK and t h e v isible p rocedur e P1 . Add it ion ally , t h er e is a bu sineess es. er edeinclude: second p ack age, AX. An AX pr ocedu re uses t he pr ocedur e P1 . View in g const r aint s in t h e dat a dict ion ar y

Figu r e 9 - 5 . Pa ck a ge Body Ref e r en cin g Anot he r Pa ck ag e.

Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] The b ody of AX is dependent on t he specificat ion of PK. Specif ically , t he b ody of t h e pr oced ur e A1 calls PK. P1.

The b ody of] AK becom es inv alid if w e r ecom pile t h e PK specificat ion. Th e body of AK becomes [ Team LiB inv alid if w e r ecom pile t h e AK specificat ion—r ecom piling a p ack age sp ecificat ion alway s inv alidat es t he b ody . Recomp ilin g t he PK b ody or AX bod y has n o im pact t o ot her code. Th is is alway s t h e case. For any p ackag e, r ecomp ilin g t he pack age b ody is an isolat ed event t hat w ill not aff ect any ot h er st or ed pr ocedur e. Recomp ilin g a pack age specif icat ion w ill inv alidat e t h e associat ed p ack age body . I t may also aff ect t he bodies of ot her p ack ages. This w ou ld be t he case w hen t he bod y code calls pr oced ur es in t he r ecom piled spec. The f ollow in g su mm ar izes t he p ack age com pilat ion ord er . Recomp ilin g PK specif icat ion for ces: •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Recomp ilin g PK bod y and AK b ody .

By Kevin Owens

Recomp ilin g AK specif icat ion for ces: Pub lish er: Prent ice Hall PTR Pub Dat e:Recomp Decem berilin 0 5,g2AK 003

body .

I SBN: 0- 13 -0 850 33 -0

Recomp ilin g eit her PK body or AK b ody aff ect s not hin g. Pages: 44 8

9.8.2 Scenario 2 Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Tw o p ack can t heir depend en teront oeach otrhuct er 'ur s ed pack age specif ion( SQL) . The, an d Kevin Ow ages ens ex plorhav es e PL/ SQL,bod Oryacle's answ t h e St Query Languicat age follow ingyou illust rat es t his case. t eaches w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. The f ireasyst pack is PK. e second pack ageples, is AX. PK p rocedu res rtefer en ces Using t o-age follow instTh r uct ions an d ex am t hisA book pr esent echniq uesan t o AK t ake pr oced AnOr AX pr oced ures e r such ef erences a gers PK prand ocedstur e. See Figur 9-f6eat . u r es t hat allow y our adv ant ur age. e of acle feat ur as t rig ored pr oced ureesdat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: PK.print_something_else calls AX.print_square_of_2 AX.print_something_else calls PK.print_time View in g const r aint s in t h e dat a dict ion ar y Com plex r uleFigu enf orcem r e 9en - 6t .

Tw o I n t e r dep en den t Pack a ge s.

PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] To com pile t h e fou r pr ogr am u nit s, t w o specs and t w o bodies, t he p ack age sp ecificat ions m ust b e comp iled fir st , t h en t he bodies. The code f or t h is sh ow s t he p ack age sp ecificat ions fir st , t h en t h e bodies.

[ Team LiB ]

CREATE OR REPLACE PACKAGE pk is PROCEDURE print_time; PROCEDURE print_something_else; END pk; / CREATE OR REPLACE PACKAGE ax is PROCEDURE print_square_of_2; PROCEDURE print_something_else; END ax; / •

Table of Content s

CREATE REPLACE BODY Pr ogr am mOR ing Or a cl e ® Tr i PACKAGE gger s and Stor e d Ppk roceis dure s, PROCEDURE print_time IS By Kevin Owens begin dbms_output.put_line(SYSDATE); END print_time; Pub lish er: Prent ice Hall PTR PROCEDURE print_something_else IS Pub Dat e: Decem ber 0 5, 2 003 BEGIN I SBN: 0- 13 -0 850 33 -0 ax.print_square_of_2; Pages: 44 8 END print_something_else; END pk; /

Thir d Edi ti on

CREATE Ef fect ively ORcreat REPLACE e an d PACKAGE man age com BODY plex axdat isabases w it h Or acle! Sy st ems and dat ab ase ex per t print_square_of_2 KevinPROCEDURE Ow ens ex plor es PL/ SQL, Or acle'sIS answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches begin you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. dbms_output.put_line(SQRT(2)); UsingEND easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake print_square_of_2; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat abPROCEDURE ases t o incor por at e bu siness r ules w hich print_something_else IS ar e easy t o man age and m odif y as t he bu sinBEGIN ess evolv es. Topics cov er ed include: pk.print_time; END print_something_else; View in g const r aint s in t h e dat a dict ion ar y END ax; / Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Recomp ilin g h as t he follow in g ef fect s. Dat a t y pes and comp osit e st r u ct u re Recomp ilin g PK specif icat ion for ces: Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Recomp ilin g PK bod y and AK b ody . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Recomp ilin g AK specif icat ion for ces: m or e Pr ogr am m ing Oracle s andand St or edb Pr oced Recomp ilinTr g igger AK body PK ody . ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com Recomp ilinplex g eitdat herabases. PK body or AK b ody aff ect s not hin g. [Recomp Team LiB ilin g] a bod y aff ect s n ot hing , bu t r ecom piling a sp ecificat ion cou ld h ave w id e im plicat ion s by inv alidat ing t h e body of t hat packag e plus man y ot her pack age b odies. [ Team LiB ]

[ Team LiB ]

9.9 USER_ERRORS SHOW ERRORS is a SQL* Plus com m and. I t r et u r ns inf orm at ion f rom t he USER_ ERRORS v iew , w hich has t h e follow ing descr ipt ion:

SQL> desc user_errors Name Null? Type • -----------------------------Table of Content s -------- ---------------PrNAME ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce s, Thir d Edi ti on NOTdure NULL VARCHAR2(30) TYPE VARCHAR2(12) By Kevin Owens SEQUENCE NOT NULL NUMBER LINE NOT NULL NUMBER POSITION NOT NULL NUMBER Pub lish er: Prent ice Hall PTR TEXT NOT NULL VARCHAR2(4000) Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 You can select com piler err or r esult s w hen not ru nnin g SQL* Plus by qu er y ing t his v iew . The USER_ERRORS v iew cont ains er r ors for ob ject s comp iled in y our schem a. ALL_ERRORS and DBA_ERRORS ar e ot h er view s w it h wid er scope. Ref er t o Ch apt er 5 f or a com p let e d escr ip t ion of t he diff er ences bet w een t he USER, ALL, and DBA dat a dict ion ary view s. The f ollow ing is a Ef fectipt ively d mn mans.age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t descr ion creat of t hee an colu Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. NAME This is t he nam e in t he CREATE OR REPLACE clause. This is not t he host f ile. Using easy- tRu o- follow uctipt ions an d ex am ples, twhis pr esent s tREPLACE echniq uesPROCED t o t ake URE nning tinst h e rscr @MY_HELLO.SQL it hbook a CREATE OR adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat st allow our HELLO st at em ent cr eat es t he ob ject n ame HELLO. The dat a d ict ion ary or es yall dat ab ases t oatincor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he t r ibut es in up per case. bu sin ess evolv es. Topics cov er ed include: TYPE This is FUNCTI ON, PROCEDURE, PACKAGE, or PACKAGE BODY. Ther e is nev er an un derscor e in PACKAGE BODY. View in g const r aint s in t h e dat a dict ion ar y SEQUENCE This cor r espon ds t o t he er r or num b er r elat ive t o t h e num b er of er r ors in t h e com pile. Com plex r ule enf orcem en t

LINEPL/ SQLThis is am t he un listit-sfile line nu mage ber,f eat whuich p r ogr and langu rescont ains t he er ror . Th is corr esp onds t o t h e LI NE colu m n in USER_SOURCE. Dat a t y pes and comp osit e st r u ct u re POSITION This is t he colum n p osit ion of t h e er r or . dling ions TEXTEr r or han This contand ain sexcept t he t ex t of t he er ror . For ex amp le: I nt er - pr ocess com mu nicat ions 'PUTLINE' must be declared PLS-00302: component Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch [ Team LiB ] m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Chapter Ten. PL/SQL Program Units 10 .1 PROCEDURES 10 .2 FUNCTI ONS 10 .3 SUBPROGRAM ENCAPSULATI ON: I NTRODUCTI ON TO PACKAGES 10 .4 PACKAGE SPECI FI CATI ON 10 .4 . 1 Sy nt ax an d St y le •

Table of Content s

Pr ogr am m ing ® Trelopin i gger s and ed P roce dure s, Thir d Edi ti on 10Or.4a cl . 2eDev g a Stor Specif icat ion By Kevin Owens

10 .5 PACKAGE BOD Y 10 .6 APPLI CATI ON PARTI TI ONI NG

Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003

10 .7 DATA ABSTRACTI ON I SBN: 0- 13 -0 850 33 -0

10 Pages: .8 PARAMETERS 44 8 AND MODES 10 .8 . 1 I N Mod e ( Defau lt ) I s a Const ant 10 .8 . 2 I N OUT Mode Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex. plor es Mode PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 10 .8 3 OUT t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 10 .8 . 4 Funct ions and Modes Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e 10 of .8 Or. 5acle es such asional t rig gers and Namfeat ed ur v ersus Posit Not at ionst ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv Topics cov am er ed include: 10 .8es. . 6 Defau lt Par et er s 10 .8 . 7 Scalin g Code w it h Defau lt s View in g const r aint s in t h e dat a dict ion ar y 10 .8 . 8 % TYPE Com plex r ule enf orcem en t 10 .9 OVERLOAD I NG PL/ SQL p r ogr am un it s and langu age f eat u res This chap t er pr esent s PL/ SQL f rom a soft w ar e engin eer ing persp ect iv e. PL/ SQL has t he pes and comp followDat ingaprt yogr am u nit s: osit e st r u ct u re Er r or han dling and except ions Pr ocedu r e I nt er - pr ocess com mu nicat ions Funct ion Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e e specif icat ion Packag Pr ogr Packag am m inge Oracle bod y Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int St or ellig ed en p rocedur t , com plex es ardat e PL/ abases. SQL p r ogr am un it s t hat ex ist as ob ject s in t he Or acle dat ab ase. Th e t er m " st or ed pr oced ur e" r efers t o a com p iled and callab le pr ogr am w it hin t he d at abase. [ Team LiBlem ] ent s st or ed p rocedu res as p rocedur es, fu nct ions, and pack ages. You do n ot call Or acle imp pack ages. You call t he pr oced ur es and fu nct ions w it hin t he visible par t of t he p ack age. Dat ab ase vend ors hav e diff er ent imp lem ent at ion s for st or ed pr ocedu res. SQL Ser ver Tr ansact - SQL pr ov id es pr ocedu res an d f un ct ion s but not pack ages.

Sub pr ogr am] s r ef er t o p rocedur es and f unct ions in gener al, w het her it be a st an d- alone [ Team LiB pr oced ur e/ fun ct ion or p r ocedu re/ f unct ion in a pack age. PL/ SQL p rocedur es and f unct ions m odel pr ocedur es and fu nct ions of ot h er lan guag es—t h ey receiv e par am et er s, d eclar e local v ariab les, and im plem en t som e degr ee of logic using t he con st r uct s of t he PL/ SQL pr ogr am m ing langu age. Packag es ar e p rog ram unit s t hat en cap su lat e per sist ent dat a as w ell as sub pr ogr am s. PL/ SQL is a loosely t y ped langu age. I t h andles im plicit con ver sion ; f or exam p le, y ou can p ass a NUMBER t y pe arg um en t t o a p rocedu re d esign ed t o accept a st r ing. On t he ot h er hand , Or acle perf or m s t y pe check ing at com p ile- t im e and r un- t im e. A com pile- t im e const rain t check fails if a pr ocedu r es at t em pt s t o assign a com posit e r ecor d st r u ct u re t o a scalar v ar iable. Ru n- t im e err or s occur w hen an im p licit conv er sion fails. Var iables of t yp e NUMBER are im plicit ly conv ert ed t o a VARCHAR2; how ever , if t he r un - t im e valu e is 999 9 and t he r ang e is VARCHAR2( 3) , a r un - t ime con st r aint v iolat ion occur s because 999 9 is t oo lar ge f or t he t hr eeby t e char act er st rin g. •

Table of Content s

All subp r ogr am par am et er s h ave a m ode t h at d esignat es t he dir ect ion of t he dat a—b et w een Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on t he caller and called pr ogr am . Par am et er m od es ar e I N, OUT, an d I N OUT. Most v iolat ions of By Kevin t his t ypOwens e ar e det ect ed at com pile- t ime; for ex am ple, a com pile err or occur s w hen an I N mod e v ariab le is w rit t en t o. Th is is det ect ed w hen t he I N m ode v ar iable is on t he lef t side of an assig nm en t st at em en t . I n general, t here are man y for m s of const r aint an d t yp e check ing Pubm lished er: bPrent ice com Hall PTR per for y t he piler. Run - t ime ch eck s enfor ce const r ain t s not evalu at ed at com p ilePub Dat e: Decem ber 0 5, 2 003 t im e. I SBN: 0- 13 -0 850 33 -0

PL/ SQL is a 44 langu age t h at int eg rat es sever al soft war e eng in eer ing pr incipals: inf or mat ion Pages: 8 hidin g, encapsulat ion, dat a abst r act ion , m odular d esign , and st ep w ise r efinem ent . A key feat u re of t he lang uage is t he pack age p arad ig m t hat couples t h e langu age w it h desig n. A com piled pack age specif icat ion can be r eview ed as a det ail d esign docum ent , m inim izing t he t r ansit ion fr om design t o p rog ram developm ent . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Owally ens ex plor acle's o t h e dStint r uct edpQuery ( SQL) Add it ion , PL/ SQLesintPL/ egrSQL, at es Or t he ANSIansw SQLerSttandar o ur t he rog ramLangu m ing age langu age ,inan ad tweaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ay t hat f acilit at es r apid developm ent . Exam ples of t h ese f eat u r es ar e SQL SELECT st at ement s t hat popu lat e comp osit e record st r uct ur es and cur sor FOR loop s. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv antur age et yof acle feat es such rig gers ored pr oced es- df eat u r es t that allow y our St r uct peOrdefinit ionsurcan be cras eatted in t heand d atst abase f rom wur hich at abase able colum n dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he t y pes and PL/ SQL arr ay st r uct ur es can be der ived. The int egr at ion of t y pes bet w een t he bu es. SQL Topics covs er include: datsin abess ase evolv and PL/ allow a ed p r ogr am t o select a colum n t hat st ores an ar r ay of st ru ct u r es in a PL/ SQL var iable. View in g const r aint s in t h e dat a dict ion ar y The r ob ust f eat u r es of t his langu age pr ov ide a st ron g m ot iv at ion for Jav a and . Net developer s t o im pCom lemplex ent lar ge enf pororcem t ions of r ule en tt h eir f unct ionalit y w it h PL/ SQL. A st r engt h t h at cont in ues g r owlangu w it hage PL/ fSQL PL/ SQL p r ogr am un ittso and eat uis resOr acle su ppor t for addit ional built - in pack ages. The list of pack ages pr ov ided b y Or acle is quit e ex t ensive. Followin g ar e som e exam Dat plesa of list ings. t y pes and comp osit e st r u ct u re Er r or han dling and except ions DBMS_ PI PS and DBMS_ ALERT pr ov ide a mechanism b y w hich separ at e Or acle pr ocesses can m unicat e asy nchr onously —sim ilar t o UNI X- nam ed pipes. I nt ercom - pr ocess com mu nicat ions Adv anced includes sever al pack pu sh fan d p ullk ey, dat achint o , and of Declar at iv eQueuing const r aint s, including p rim ar ages y k ey t, hat u nique, or eign eck and out m uch logical qu eu es in a dist rib ut ed en vir onm ent . m or e BMS_LOB p ack age p rovSt ides t fur oreshan dling larg e 4g ig aby t ealuable obj ect sr esou as rce Pr ogr The am mDing Oracle Tr igger s and or edsup Prpor oced , Th ir d Ed it ion , is an inv colum n v alues in a t ab le. This allows a PL/ SQL pr ocedu r e t o load a lar ge d ocum en , for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t rtuly such as a Micr osof t Word or PD F file, in nat iv e for m at , int o a t able. int ellig en t , com plex dat abases. JavLiB a in] t he d at abase allow s a PL/ SQL pack age specif icat ion t o act as a PL/ SQL API t o a [ Team bod y imp lem ent at ion using Jav a. An ex am ple w ould be a PL/ SQL packag e sp ecificat ion w r it t en in PL/ SQL w it h a p ack age body w r it t en in Jav a. PL/ SQL p r ogr ams can per for m I O t o host f iles u sing t h e UTL_FI LE packag e.

[ Team LiB Ther e ]ar e pack ages for g en er at in g r and om nu mb er s; im plem en t ing HTML ser v er - side pr ogr am s, similar t o a CGI m odel or an XML DOM API ; and m ore. Th is list is relat iv ely shor t com par ed t o t h e com p let e sw eep of API s pr ov ided b y Or acle. You can ex ecut e a st or ed p rocedur e f r om a SQL* Plus session . You can em bed PL/ SQL code in t hir d- g en er at ion langu ages: C pr ogr am s w r it t en w it h Pr o* C can includ e PL/ SQL block s and call st ored pr oced ur es. An y client - side in t erf ace, w h et h er Web or client / serv er, can inv ok e PL/ SQL p r ocedu res com piled in t he d at abase. Con nect iv it y supp ort f or PL/ SQL p rocedur es includes OD BC, JD BC, and Or acle' s Net 8. Ther e is benefit t o PL/ SQL as a lan guag e choice for Oracle sy st em s dev elop ment . Com par ed t o ot her langu ages, it t ak es less t im e t o code a com plex f unct ion w rit t en in PL/ SQL. The follow ing discussion add resses som e considerat ion s w hen plannin g w h at pack ages y ou mig ht dev elop and how t hey m ight int er face w it h each ot her . [• Team LiB ] Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

10.1 Procedures A PL/ SQL pr oced ur e is a st an d- alone p rog r am t hat y ou com pile int o an Or acle d at abase sch em a. Procedur es can accept arg um en t s. When you com pile a p rocedu re, t h e pr oced ur e ident if ier of t h e CREATE PROCEDURE st at em ent becom es t he object n am e in t h e dat a dict ionar y . Figur e 10 - 1 illust r at es t he com pon en t s and k ey w or ds of a pr oced ur e. This st r uct ur e app lies f or a st an d- alone p rocedur e an d t he pr ocedur e code of a packag e bod y.

Figu r e 1 0 -1 . Pr oce dur e . •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he The k ey com ponent s of a pr oced ur e t o wh ich y ou wr it e code are t he f ollow ing : bu sin ess evolv es. Topics cov er ed include: Declar at ivineg const Thisr aint is wshin er et hyeou v ar View datdeclar a dicteion ariab y les, f or exam ple: Par t local_counter Com plex r ule enf orcem en t NUMBER := 0; Youam m ay havlangu e t y pe d ef inituions. PL/ SQL p r ogr un italso s and age f eat res Ty pe def in it ions w ould be r equ ir ed for com posit e st ru ct u r es such as r ecor ds and index - by t ab les. You m ay code oced ur esosit and furnct Dat a t y pesprand comp e st u ctions u re w it hin t he declar at iv e par t . For exam p le, y ou m ight w r it e a local f unct ion t hat r et u rn s a sub st rin g w it h cer t ain char act er ist ics. You could u se t his Er r or han dling and except ionslocal f unct ion t o m ak e t he b ody easier t o r ead . Youcom canmu d eclar ex cept ions h er e. I f you d eclar e an ex cep t ion w it h in a I nt er - pr ocess nicateions pr oced ur e y ou sh ould handle it locally . No pr ogr am t hat calls you r pr oced ur e Declar at iv ecan const including rim ar y klocal ey , ut nique, orocedur eign k ey, capr aint t ur es,except ions pt hat are o y our fpr e. ch eck , and m uch m or e Sub pr ogr am The su bpr ogr am b ody cont ains t he logical algor it hm imp lem ent ed wit h Body PL/ SQL con t sroland conSt stor rued ct s.PrPL/ SQL supp loops, en -inv else st r uctrur es, rce Pr ogr am m ing Oracle Tr igger oced ur es , Thort ir ds Ed it ion ,if-ist han aluable esou st at em ent s,erand d eclar b lock st r uct ur es. for dat abase d evcase elopers, d esign s, and pr oje-ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. Ex cep t ion The ex cep t ion h andler is opt ion al. The ex cept ion han dler is sim ilar t o t he t r y cat ch m odel in ot h er lan guag es. You can cod e an ex cep t ion h andler f or a han dler [ Team LiB ] specif ic t y pe of err or or w rit e a gener al- pur pose ex cept ion han dler. You should nam e a pr ocedu re wit h a ver b. Pr ocedur es usually per for m som e act ion su ch as up dat e t h e dat ab ase, w r it e t o a f ile, or send a m essag e.

[ Team LiB ] A p r ocedu re n eed not hav e par am et er s. Wh en cr eat in g a pr oced ur e do not use par ent heses if t her e ar e no par am et er s. Close par ent heses are opt ional wh en callin g t he pr ocedur e. The follow ing illust rat es t he absence of par ent heses. First , cr eat e a t ab le.

CREATE TABLE TEMP(n NUMBER);

The p r ocedu re I NSERT_TEMP insert s a r ow int o t h e t able TEMP. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

PROCEDURE insert_temp IS BEGIN Pub lish er: Prent ice Hall PTR INSERT INTO TEMP (n) VALUES (0); Pub Dat e: Decem ber 0 5, 2 003 END insert_temp: I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

A p r ocedu re t hat uses I NSERT_TEMP can cod e eit h er of t he f ollow ing st at em en t s:

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. insert_temp; insert_temp(); Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he You S orTopics AS—eit her syninclude: t ax is accept ab le. bu sincan esscode evolvIes. cov er ed View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PROCEDURE insert_temp IS | AS PL/ SQL p r ogr am un it s and langu age f eat u res a ttyhe pesp rand comp osit ee st ct uEND re clause is opt ional, b ut high ly recomm end ed . A App enDat ding ocedu re nam t or ut he pr oced ur e can sp an sever al screens. Wh en scr olling t hr oug h cod e, it is ext r em ely h elp ful t o ErEND r or han dlingand andk now except ions see an clause you hav e n ot sk ip ped r eading int o t he next pack age pr ocedur e. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e END; -- acceptable. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly ENDprocedure_name; -- highly recommended in production. int ellig en t , com plex dat abases. [ Team LiB ] A com m on pr ocedu re st y le is t o alig n t he I S, BEGI N, EXCEPTI ON, and END. I n dent all cod e w it hin t hese key w ord s. This st y le mak es t he cod e easier t o read. The f ollow ing illust r at es a pr oced ur e t hat pr int s t he av erag e and sum of v alues in a t ab le. Th e code sect ion bet w een t he I S an d BEGI N is called t he declar at ive par t of t h e pr oced ur e.

[ Team LiB ]

PROCEDURE print_temp IS v_average NUMBER; v_sum NUMBER; BEGIN SELECT AVG(n), SUM(n) INTO v_average, v_sum FROM TEMP; dbms_output.put_line('Average:'||v_average); dbms_output.put_line('Sum:'||v_sum); END print_temp; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

A st an dalone p rocedur e f r eq uent ly evolv es int o a new p ack age or m er ges w it h an ex ist ing By Kevin Owens pack age. Con sider t he pr oced ur e, I NSERT_TEMP, show n on p. 2 51, wh ich insert s a n um ber int o t he TEMP t ab le. The m igr at ion of I NSERT_TEMP int o a p ack age is a simp le ed it ing pr ocess hatPrent p r oduces t he f ollowin g: Pub lisht er: ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

PACKAGE temp_operations IS PROCEDURE insert_temp; Ef fecttemp_operations; ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t END Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn owISt o build rob ust an d com plex dat ab ases f or y our b usiness. PACKAGE BODY temp_operations PROCEDURE insert_temp IS UsingBEGIN easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag eINSERT of Or acle feattemp ur es such t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our INTO (n) as VALUES (0); dat abEND asesinsert_temp; t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sintemp_operations; ess evolv es. Topics cov er ed include: END in IgNSERT_TEMP const r aint s inchang t h e dat dict ion y t o use t he new int er face: The uView ser of es at heir PL/ar SQL Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re temp_operations.insert_temp; temp_operations.insert_temp(); Er r or han dling and except ions I nt er - pr ocess com mu nicat ions [ Team LiB ] Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

10.2 Functions Som e langu ages hav e a sing le su bpr og ram t yp e. A Jav a class has m et hod s and a m et hod m ay or m ay not r et ur n dat a. Th e C lan guag e is t he sam e. The on ly su bpr ogr am in C is a fu nct ion. A C fun ct ion can ret u rn a value or m odify t he cont ent s of an ad dr ess v alue p assed as an ar gum ent . PL/ SQL in clu des t w o t y pes of sub pr ogr ams: pr oced ur es and fun ct ion s. Consider a packag e t o be t he encapsulat ion of operat ion s on som e ob ject . That obj ect can b e a t ab le, d at abase pip e, host file, t ables in a r em ot e dat abase, or m any ot her opt ions. Pr ocedur es t ak e act ions on t he obj ect and m odify t hem. Fu nct ions p rov ide a m ean s t o acqu ire st at u s or st at e in for m at ion •abou t t h e obj Table ect . of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

The p ackag e t yp ically b eh aves as an API t h at h id es an ob ject an d p rov ides op er at ions on t h e By Kevin Owens obj ect . I f t h e user needs t o kn ow , for ex am ple, how lar ge t he ob ject is, a m et hod m ust b e av ailab le. Fun ct ion s play t h is r ole. Fun ct ion s fr equent ly act as select or s on an ob ject . Pub lish er: Prent ice Hall PTR

Con sider t he fu nct ion t o b e t he ev alu at ion of an at t ribu t e of an obj ect . Fun ct ion s ar e not Pub Dat e: Decem ber 0 5, 2 003 act or s, but r at her evaluat ion s of a st at e. You should use n ouns t o nam e f unct ions. I SBN: 0- 13 -0 850 33 -0 8 Figur ePages: 10 - 2 44 illust r at es t he com pon en t s of a f un ct ion . The k ey comp onent s of a fu nct ion, t o w hich you w r it e code, ar e t he f ollow in g:

Declar at iv e This w h erage e y com ou declar e v abases ar iab les,w it f or exam ple: Ef fect ively creat e an dis man plex dat h Or acle! Sy st ems and dat ab ase ex per t Par t Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d Kevin local_counter := 0; t eaches you w hat y ou n eed t o knNUMBER ow t o build rob ust an d com plex dat ab ases f or y our b usiness. You minst ay ralso havan e tdy pe d efples, init ions. pe def in it ions w ould ues be r tequ ir ed for Using easy- t o- follow uct ions ex am t hisTy book pr esent s t echniq o t ake e es st rusuch ct u r es as r and ecor st dsored and pr index byest abf eat les.u rYou m ayallow code y our adv ant ag e of Orcom acle posit feat ur as such t rig gers oced- ur es t hat pr oced fu nct ionsww it hinarteheeasy declar iv eage par and t . Form exam le,t he y ou m ight dat ab ases t o incor por aturees buand siness r ules hich t o at man odif y pas w rTopics it e a local f unct ion t hat r et u rn s a sub st rin g w it h cer t ain char act er ist ics. bu sin ess evolv es. cov er ed include: You could u se t his local f unct ion t o m ak e t he b ody easier t o r ead . Your aint can sdin eclar ex cept ions View in g const t h ee dat a dict ion harery e. I f you d eclar e an ex cep t ion w it h in a pr oced ur e y ou sh ould handle it locally . No pr ogr am t hat calls you r pr oced ur e Com plex r ule en t canenf caporcem t ur e except ions t hat are local t o y our pr ocedur e. PL/ SQL p r ogr un it s and langueage f eat u rest hat is t h e var iable t o be r et ur ned. You Youam fr equent ly d eclar a v ar iable m ust r et ur n somet h in g in a fun ct ion . I f t he f unct ion r et u r ns a NUMBER, t h e Dat a t y pesNUMBER and comp osit e st rcould u ct u rebe declar ed. That v ariab le w ould b e used in t h e var iable RETURN st at ement . Er r or han dling and except ions Sub pr ogr am The su bpr ogr am b ody cont ains t he logical algor it hm imp lem ent ed wit h com mu ionsst ru ct s. PL/ SQL supp ort s loops, if- t h en - else st r uct ur es, PL/ SQL connicat t rol con BodyI nt er - pr ocess case st at em ent s, and d eclar e- b lock st r uct ur es. The b ody m ust in clu de a Declar at iv eRETURN const r aint s,ement including p rim ar yit kw eyill, u nique, f or eign k ey, ch eck , and m uch st at , ot her wise not com pile. m or e Ex cep t ion The ex cep t ion h andler is opt ion al. The ex cept ion han dler is sim ilar t o t he t r y cat chTr migger odel sinand ot hSt eror lan es. ur You e itan t ion andler fror a rce Hand lerm ing Oracle Pr ogr am edguag Pr oced es ,can Th ircod d Ed ionex, cep is an invhaluable esou ic t ydpe of err or and or wpr ritoje ect a gener al-s pur pose cept Make for dat abase d evspecif elopers, esign er s, leader look in g tex ob uildion anhan d mdler. aint ain t r uly sur e dat t heabases. ex cep t ion h andler includes a RETURN st at em ent . int ellig en t , com plex [ Team LiB ]

Figu r e 1 0 -2 . Fun ct i on.

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

Par amPages: et er s 44 ar8e opt ion al, but t he RETURN p art is not . The FUNCTI ON st at em en t m ust in clu de a RETURN an d a t y pe. The RETURN st at em en t , in t he sub pr ogr am b ody , is a k ey comp onent . A fu nct ion com pilat ion fails if t h er e is n o RETURN st at ement in t he b ody of t he cod e. A fu nct ion t hat follow s an Ef fect ively creat an ends d manbefor age ecom plexing dataabases w it h Orem acle! st ems ex. per execut ion pat h teh at execut RETURN st at entSy cau ses aand ru n-dat t imab e ase er ror A t Kevin Owmu ensst ex plor PL/ SQL, stOr er tpile; o t h eitStmr uct ed Query Langu age , an d fu nct ion hav e es a RETURN atacle's em entansw t o com u st ur execut e a RETURN dur( SQL) ing r untt eaches hat y ou n eed rob usthan d comand plexnot datinclude ab ases af or y our b usiness. im e. A fyou requwen t ov ersigh t ist ot oknwow r it et oanbuild ex cep t ion andler RETURN clau se. A f un ct ion t hat ent er s an ex cep t ion h andler w it hou t a RETURN st at em ent generat es a r unUsing easyt im e err or . t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ases in t og incor siness hich arae DATE easy ttoy pe. manThe agedand Theab f ollow ex ampor pleatise abuf un ct ionr ules t h at w r et ur ns eclarmatodif iveypas ar tt he cr eat es t h e bu sin ess evolv es. Topics cov er ed include: v ariab le NEXT_DAY par t . Th e pr ogr am b ody assig ns a value and ret u rn s t hat v alu e. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t CREATE OR REPLACE FUNCTION tomorrow RETURN DATE PL/ SQL p r ogr am un it s and langu age f eat u res IS next_day Dat a t y pesDATE; and comp osit e st r u ct u re BEGIN next_day := SYSDATE + ions 1; Er r or han dling and except RETURN next_day; END tomorrow; I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Funct m ions or ecan include an ex pr ession in t h e RETURN st at em ent . This oft en m ean s less code in t he fun ct ion b ody . The f ollow ing f unct ion per for m s t he sam e logic as t he pr eced in g fun ct ion . Pr am m ingp le, Oracle Tr igger and St oced uryes I n ogr t his exam t h e local vars iable isor n ed ot nPrecessar . , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] FUNCTION tomorrow RETURN DATE IS BEGIN

RETURN [ Team LiB ] SYSDATE + 1; END tomorrow;

I f t her e ar e no p ar amet er s, do n ot u se em pt y par en t heses in t he fun ct ion d ef init ion. Th is ru le app lies t o pr oced ur es as w ell. Th e user of t he f unct ion can u se t he f unct ion as a sing le exp ression t h at ev alu at es t o som e t y pe. The follow in g cod e uses t he TOMORROW f un ct ion in an assign m en t st at em en t . The sam e pr ocedur e uses t h e fun ct ion as an ar gu ment t o DBMS_ OUTPUT.

CREATE OR REPLACE PROCEDURE tomorrow_user IS • Table of Content s my_date DATE; Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on BEGIN my_date By Kevin Owens := tomorrow(); my_date := tomorrow; dbms_output.put_line('Tomorrow is '||tomorrow); ENDPub tomorrow_user; lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

Use f un ct ion s t o in cr ease t he r eadabilit y of t he cod e. The f ollow ing uses t he TOMORROW Pages: 44 8 fu nct ion in a loop. The cod e is clear an d id en t ifies w hen t he loop st ops.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tWHILE eacheslocal_date_variable you w hat y ou n eed t o kn t o build LOOP rob ust an d com plex dat ab ases f or y our b usiness. < ow tomorrow Loop body Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake END LOOP; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es.nct Topics covar ereedalw include: Var iables and fu ion calls ays in t er chan geable pr ov id ed t h e fu nct ion r et ur ns t he sam e t yp e as t h e var iable. For exam p le, t h e TOMORROW f unct ion ret u rn s a D ATE t y pe. An y PL/ SQL st at em ent , in w hich a DATE v ariab le is accept ab le, can use t he fun ct ion TOMORROW. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res PROCEDURE Dat a t ysample pes and comp osit e st r u ct u re IS today DATE; Er r or han dling and except ions BEGIN today tomorrow 1; ions I nt er - pr:= ocess com mu nicat dbms_output.put_line(tomorrow - 1); END sample; Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr amLiB m ing [ Team ] Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

10.3 Subprogram Encapsulation: Introduction to Packages Packag es pr ovid e a m ech anism t o log ically gr oup sm aller p rog ram unit s t oget her . The gr oup ing of pr ocedu r es in t o a packag e m odular izes t he code. Ph ysically , t h e use of pack ages m ean s few er files and f ew er m odu les t o m anage. Pr ogr am m er s ar e m or e inclined t o r eu se m odular cod e. Pr ogr am mer s w ho begin w ork ing on t he sy st em , b uilt w it h pack ages, quick ly gr asp t h e ov er all ar chit ect ur e because t hey can lear n t he sy st em in a t op- dow n f ash ion —lookin g at •w hole m odu les Table anofd Content h ow t hs ey in t er f ace. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Figur e 10 - 3 illust r at es t w o p rocedu res. To g r ant t he use of t h ese p rocedur es t o ot her By Kevin Owens app licat ions requ ir es a GRANT EXECUTE on each pr oced ur e. I m agin e 50 pr oced ur es. Add it ion al f unct ionalit y m eans m or e pr oced ur es, m or e gr an t s, and m ore f iles. Pub lish er: Prent ice Hall PTR

Figu re 1 St a nd- Al one Pub Dat e: Decem ber00-3 5, 2.003 I SBN: 0- 13 -0 850 33 -0

Pr oce du r es a s Com pon en t s i n an Ap pli ca t ion .

Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Add it ion allyt o, aincor st ande pr oced ur e can sendarand r eceive scalar er sy was it ht he a t yp e of dat ab ases poralon at e bu siness r ules w hich e easy t o man age par andam met odif NUMBER, VARCHAR2 , and DATE. The lang uage allow s y ou t o d ef ine com posit e st ru ct ur es bu sin ess evolv es. Topics cov er ed include: such as r ecor ds. A st an d- alone p rocedur e cann ot r et ur n a com posit e r ecor d st r u ct u re unless anot h er packag e specif icat ion defin es t hat st r uct u re. Rely ing on in div id ual p rocedur es and fu nct ions lim it ingr aint in lar ent Viewis in g const s gein t scale h e datdevelopm a dict ion ar y. Pr ocedu r es P1 ran d enf P2 orcem can been easily m er ged in t o a sin gle pack age. This m ak es sense if t hese Com plex ule t pr oced ur es per for m r elat ed oper at ions. Pr ocedu r e P1 d oes an I NSERT. Pr ocedu r e P2 does a PL/ SQL p r ogrtam unSQL it s and rest he sam e t able. SELECT. Consider hese st atlangu ementage s t of eat b e uon y pes and comp osit st r uying ct u ret h e pr oced ur e bod y of each int o a single p ack age The mDat igr aat tion pr ocess in clud ese cop bod y. The pr ocedur e int er face d ef init ions becom e t he p ack age sp ecificat ion. Af t er t his, y ou Er rnew or han dlingurand except ions include pr oced es and fu nct ions t o en hance t h e over all f unct ionalit y of t h e packag e. Figur e 10 - 4 sh ows t he encapsulat ion of pr oced ur es P1 an d P2 int o a sing le packag e. I nt er - pr ocess com mu nicat ions

Figu r e s,1 including 0 -4 . En pcap suy la t i,on of Prf oroce r es. Declar at iv e const r aint rim ar k ey u nique, eigndu k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Aft er t he pack age is com plet e, t he specificat ion ( sh own in t he t op r igh t of Figur e 10 - 4) is comPub piled , t hen heHall b ody lish er: Prent tice PTR. Add it ion al pr oced ur es and fu nct ions ar e add ed t o t he p ack age. Pub Dat e: Decem ber 0 5, 2 003

[ Team LiB ]

I SBN: 0- 13 -0 850 33 -0

Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

10.4 Package Specification Pr ogr am min g h as alw ays in volv ed t h e " pack aging " of r elat ed pr ogr am s. This includ es com pilin g a gr oup of pr og ram s int o a sing le obj ect lib rar y an d conf igur ing t he cod e of a single sub sy st em und er one sour ce code dir ect or y . Con figu rat ion m anag em ent t ools allow us t o packag e our sof t w are u nder log ical an d fun ct ion al subj ect ar eas so developer s can easily locat e pr ogr am s for ch eck - out and check - in pur p oses. For some en vir onm ent s, t h e high est abst ract ion of a u nit of sof t w are is a pr ocedur e. The m anagem ent of t he soft w ar e r eposit ory t hen b ecom es t he m an agement of m any ind ividu al pr ogr am s. For ot her lang uages, pr ocedur es t hat collect ively sat isf y a m aj or fu nct ional •r eq uir em ent Table Content s e object m od ule, m anaged as one sof t w are u nit . Th is is t he case com pofile in t o on Pr ogr am m ing Or a cl e ® Tr i gger s Stor ed P dure s, Thir d Edi ti on w it h C p rog r amm ing w her eand m ult iple Croce fu nct ions com pile as one C ob ject f ile. Jav a packag es cont ain Jav a classes and t he com piler r elies on a m at ch bet w een dir ect or y an d p ack age By Kevin Owens nam e. A p rPub ogrlish amm er w need er: Prent iceho Hall PTR s t o use a p rocedur e m ust fir st ident if y t he mod ule and t h en ident if y t he Pub sp ecific f un ct ion , pr oced ur e, or m et h od need ed . The C lang uage u ses a header f ile, a Dat e: Decem ber 0 5, 2 003 sep arat e file f rom t he C algor it hm ic code, t hat def in es t he int er face—t his is t he fir st st ep in I SBN: 0- 13 -0 850 33 -0 learn in g how t o use anot h er pr ogr am mer 's C code. Pages: 44 8

Com plex it y of a pr og ram m ing langu age and t h e pr ogr am m in g en vir onm ent hinder s dev elop ment . I D Es ar e v ery successf ul w it h helping dev eloper s qu ick ly locat e r eu sab le pr ogr am s t h at ar e par t of t he d ev elopm en t env ir onm en t . Man y of t hese I D E t ools allow you tEf o fect addively you rcreat newelyan dev eloped o t hedat libr ar y r ep —t hisSyenab lesand a dev eloper d man agecode com tplex abases wosit it h or Oryacle! st ems dat ab aset oex per t sear chOw forens a par icular int er faceOr and easily locat of anot developer . Or acle' s , an d Kevin ex tplor es PL/ SQL, acle's answ er e t ot h t heeAPI St r uct ur ed her Query Langu age ( SQL) JDev elopyou er an Procedur e Bu erow ar e t ools h atan p rov ide plex t his dat t y pe r apid elopm ent t eaches wd hat y ou n eed t oildkn t oI DE build rob tust d com abof ases f or dev y our b usiness. env iron ment supp ort . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Wit t t he eofuse of anfeat I DE, t hesuch f eatas u res ofgers a langu canprlead am s ofallow code y our advhou ant ag Or acle ur es t rig and age st ored ocedt oursm es-all f eat u roun es tthat rdat eu ab se.ases Onet o of incor the m ostat pow ul feat ur eswof PL/ar SQL is t ht eo sim licit yand of tm h eodif packag por e buerf siness r ules hich e easy manp age y as tehe specif icat ion . The SQLcov langu age r equir es t hat t he int er f ace t o a p r ogr am collect ion bu sin ess evolv es. PL/ Topics er ed include: com pile int o a sin gle pr og ram unit . Th is pr ogr am u nit , t h e packag e specif icat ion , is not com plex . I t sim ply d ef ines t he API . Th e pack age bod y cont ains t he det ails of t he log ic. View in g const r aint s in t h e dat a dict ion ar y You can incor por at e PL/ SQL pack age specif icat ion in t he d esign pr ocess. High - lev el desig n Comdplex r ulehigh enf-orcem ener t faces and docum ent ing w hat an imp lem ent at ion w ill do. Th e includes ef ining lev el int pack age specif icat ion ident if ies in t erf aces an d in clu des and uses code and com ment s t o SQL amA un langu age f eat res can r epr esent t he com plet e t op- lev el defin ePL/ t he in t perr fogr ace. setit sofand packag e specif icatuions design of a sy st em . A packag e body wit h p seud ocod e and comm ent s can r ep r esent t he Dat a t y pes and comp osit e st r u ct u re det ailed d esign. Er r or han dling and except ions I n t heory , shou ld y ou see t he code t o a p ack age sp ecificat ion on a pr ogr am m er ' s desk, y ou should k now w het h er e at t h e t ail end of t he design p hase or t he beginnin g of t h e I ntnot er - pr ocess com mut hey nicatar ions code p hase. The pack age specif icat ion ov erlap s t he d esign and coding ph ase. Th e pack age specifDeclar icat ionatdef es a rset er faces p and p er for fmored on kaey, setchofeck obj, ect iv einconst aintofs, int including rimoper ar y kateyions , u nique, eign ands,msuch uch as t ablesmin a schem a. I t is also a com p iled obj ect in t h e dat ab ase, sub ject t o sy nt ax ru les an d or e dat ab ase pr ivileges. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Thedat p ackag ecificat iondis a single ASCIprI oj file com p rog ram for abasee dspev elopers, esign er s, and ectt hat leader s piles look inas g at osingle b uild an dm aintunit ain . t The r uly pack age b ody is also a sing le ASCI I file. The body com piles only af t er a successful int ellig en t , com plex dat abases. com pilat ion of t h e specif icat ion. You can pu t t h e specif icat ion in t he sam e file as t he bod y. [ Team LiB ]

10.4.1 Syntax and Style

The b asic e sp ecif icat ion syn t ax is: [ Team LiBpackag ]

CREATE PACKAGE package_name IS Type definitions for records, index-by tables, varrays, nested tables Constants Exceptions Global variable declarations PROCEDURE procedure_name_1 (parameters & types); PROCEDURE procedure_name_2 (parameter & types); FUNCTION function_name_1 (parameters & types) RETURN type; •END package_name; Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Ther e is no or der t o t h e pr oced ur es and fu nct ions in t he specificat ion. Pu t t h em in a logical or der t hat suit s t h e dev eloper . lish er: e Prent ice Hall ThePub p ackag body w illPTR in clud e t he PL/ SQL code f or each of t he su bpr ogr am s in t he Pub Dat e: Decem ber 0 5,bpr 2 003 specif icat ion . Each su ogr am in t h e sp ecif icat ion m ust h ave an accomp any ing su bpr og ram bod y. I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

The p ackag e sp ecificat ion can d eclar e dat a t yp es su ch as a r ecor d t yp e, dat a declar at ions such as a r ecor d, and except ions. All d at a ob ject s declar ed in t h e pack age specif icat ion ar e global. Theref ore, on ly declar e w hat needs t o be glob al. Ef fect ively creat e st anatdem man plex age dat abases it hding Or acle! Sybpr st ems and ndat ab ase ex per t The PROCEDURE entage in tcom h e pack bod y, inwclu t he su ogr am ame, p aram et er Kevin Ow ens acle's answ er t omt hust e St uct Langu SQL) an d nam es, par amex etplor er mesodPL/ es,SQL, an d Or p aram et er t y pes, mrat churted he Query PROCED UREage st at (em en t, in tt eaches you wion. hat Th y ou n eed holds t o kn ow build ust anON d com plex he sp ecificat e same t r uteo for t herob FUNCTI subp rog dat ramab . ases f or y our b usiness. Using easy- et ofollow inst r uct ionst han d eceding ex am ples, t his book The p ackag body t em plat e for e pr specificat ion pr is:esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y CREATE PACKAGE BODY package_name IS PROCEDURE procedure_name_1 (parameters & types) Com plex r ule enf orcem en t IS local variables PL/ SQL p r ogr am un it s and langu age f eat u res BEGIN code Dat abody t y pesof and comp osit e st r u ct u re END procedure_name_1; Er r or han dling and except ions (parameter & types) PROCEDURE procedure_name_2 IS I nt erlocal - pr ocess com mu nicat ions variables BEGIN Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch body_of_code m or e END procedure_name_2; FUNCTION function_name_1 (parameters & types) RETURN type Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce IS for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly local variables int ellig en t , com plex dat abases. BEGIN body of code [ Team LiB ] RETURN statement; END function_name_1; END package_name;

[ Team LiB ] A p ack age sp ecificat ion m ay declar e ex cept ion s. Let 's m od if y PACKAGE_NAME so it declar es an ex cept ion. Th e except ion nam e is I NVALI D_OPERATI ON. Th e pack age code is t h e same, bu t w it h an ex cep t ion declar at ion. Except ions are som et imes d eclar ed all in t he beginnin g of t he sp ec, som et im es all at t he bot t om . Most imp ort ant , com m en t s should indicat e w hich subp rog r ams pot ent ially r aise w hich ex cept ions.

CREATE PACKAGE package_name IS invalid_operation EXCEPTION; PROCEDURE procedure_name_1 (parameters & types); PROCEDURE procedure_name_2 (parameter & types); FUNCTION function_name_1 (parameters & types) RETURN type; •END package_name; Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

The u ser of PACKAGE_NAME h as a q uest ion : " Wh at p rocedur es r aise t his except ion?" Assu m in g t he answ er is PROCEDURE_NAME_ 1, t h e applicat ion cod e, sh ould it choose t o hanPub dlelish a er: p ossible Prent ice ex Hallcept PTR ion , look s lik e t h is: Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

BEGIN other code, etc Ef fectpackage_name.procedure_name_1(parameters); ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevinother Ow enscode, ex ploretc es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tEXCEPTION eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. WHEN package_name.invalid_operation THEN do something; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake END; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: A p ack age sp ecificat ion can also d eclar e t y pe def in it ion s such as r ecor ds. I f a p rocedur e is t o r et ur n a st udent nam e an d st at u s, t he op t ion ex ist s t o d eclar e a r ecor d t y pe in t he specifView icat ion as f ollow in g, const r aints:s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res CREATE package_name DatPACKAGE a t y pes and comp osit e st rIS u ct u re TYPE Er r or student_rec_type han dling and except ions IS RECORD ( student_name students.student_name%TYPE, I nt erstatus - pr ocessstudents.status%TYPE); com mu nicat ions Declar at iv e get_student const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch PROCEDURE m or e(stud_id IN students.student_id%TYPE stud_rec OUT student_rec_type); Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly ENDdat package_name; int ellig en t , com plex dat abases. [ Team LiB ] The p ackag e user s shou ld d riv e t h e desig n. You should consider t he u ser com m unit y w h en designing t h e sp ecif icat ion. Ov er loading of pr ocedur es and fu nct ions is a fr equent t ech niqu e t o mak ing a packag e int erf ace accept ab le t o a w id e aud ience. A reasonable sug gest ion t o t he pr ior PACKAGE_NAME specif icat ion is t o declar e a fu nct ion in t he sp ec and hav e t his r et ur n a

st udent LiB r ecor [ Team ] d t y pe. Why ? Because it can m ak e t he ap plicat ion using t h e packag e easier t o w r it e and easier t o read. Such a m odificat ion ch anges t h e specif icat ion t o t he f ollow ing :

CREATE PACKAGE package_name IS TYPE student_rec_type IS RECORD ( student_name students.student_name%TYPE, status students.status%TYPE); PROCEDURE get_student (stud_id IN students.student_id%TYPE stud_rec OUT student_rec_type); •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

FUNCTION student IN students.student_id%TYPE) RETURN student_rec_type; END package_name; By Kevin Owens (stud_id

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 0- 13 -0 850 33 -0 10.4.2I SBN: Developing a Specification Pages: 44 8

A Booch ( Gr ady Booch) diag ram , show ing j ust on e pack age in Figur e 10 - 5, is an excellen t par adig m for design . These diagr am s ar e easy t o w hit eboar d for t ech nical gr oup discussion. They pr ov ide a clear im age of t h e soft w ar e ar ch it ect u re. Booch diagr am s specif y w hat Ef fectatively an d enables man age one comtplex datatabases h Or acle! Syen st ems and dat ab oper ions creat ex ist .e This o look t he syw stitem r equ ir em t s and j udge if ase t he ex per t Kevin ens ex plor es PL/sat SQL, acle's er tts. o t h e St r uct ur ed Query Langu age ( SQL) , an d oper atOw ions d esigned w ill isf y Or t he r equansw ir em en t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

Figu r ean1d0ex -5am . St u den s Paprck ag se.t echniq ues t o t ake Using easy- t o- follow inst r uct ions ples, t his tbook esent adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch We b eg in t h is sect ion wit h a sof t w ar e r eq uir em ent t o im plement pr ocedur es t hat per for m m or e oper at ions on t he STUDENTS t ab le. Ch apt er 4 in clu des t he D DL, ent it y diagr am , and sam ple dat a for a st ud en t ap plicat ion . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly We h ave som e soft w ar e t o w rit e. Fir st , w e need t o im plem ent t he f ollowin g: int ellig en t , com plex dat abases. [ Team LiB Add a ]new st udent . Ret ur n t he t ot al nu m ber of st udent s.

We b eg in [ Team LiBw ]it h a m odel d ep ict in g t hese op er at ions. Th ese op er at ions belon g t oget her in a pack age b ecause t h ey each perf or m fu nct ions on t he st u dent ' s t able. The packag e nam e w ill be STUDENTS_ PKG. The d ev elopm en t m u st t r ansit ion f r om t he g r aphical m odel t o an in t erf ace desig n. We u se t he pack age specif icat ion as a v eh icle f or descr ibing t h is int erf ace. The f ollow ing par agr ap hs illust rat e t he d ev elopm en t t ow ar d an in t erf ace sp ecificat ion.

ADD_STUDENT SUBPROGRAM Below is a list of t h e colu m ns of t h e STUDENTS t ab le. Also r efer t o t he STUDENTS t able D DL in t he d at a m odel d em o of Ch apt er 4 ( p. 14 6) .



STUDENT_I Table D of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

STUDENT_NAME

By Kevin Owens

COLLEGE_MAJOR Pub lish er: Prent ice Hall PTR STATUS Pub Dat e: Decem ber 0 5, 2 003

STATE I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

LI CENSE_NO The STUDENT_I D colum n is t he p r im ar y k ey and is gener at ed w it h t he sequence STUDENTS_PK_ SEQ. Th is colu mn v alue is d et er m in ed in t he body of t h e ADD_ STUDENT Ef fect creatweillanuse d man com plex abases w it h Or acle! andstdat ab en aset . ex per t pr ocedively ur e and t h e age seq uence at t rdat ibut e NEXTVAL d ur ing tSy hestIems NSERT at em Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d The t hr ee colum n sy aft STUDENT_ e m andat ory v aludat es.ab Thases e last areb usiness. t eaches you w hat ou er n eed t o kn owI Dt oarbuild rob ust ancolum d comnplex f ort wy oour opt ion al. We should m ake STATE an d LI CENSE_ NO op t ional p aram et ers in t h e pr oced ur e call. Using t o-efollow inst r of uctNULL ions an ex am ples, re t his pr esent s t echniq ues t o t ake These easyw ill hav a d ef ault in dt he pr ocedu in tbook erf ace. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in gadd_student const r aint s in t h e dat a dict ion ar y PROCEDURE (v_student_name IN students.student_name%TYPE, Com plex r ule enfIN orcem en t v_college_major students.college_major%TYPE, v_status IN students.status%TYPE, PL/ SQL p r ogr am IN un it sstudents.state%TYPE and langu age f eat u res DEFAULT NULL, v_state v_license_no IN students.license_no%TYPE DEFAULT NULL); Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions An applicat ion pr ogr am can use t his int er face w it h t he follow in g call: I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e students_pkg.add_student(name, status); Pr ogr am m ing Oracle Tr igger s and St ormajor, ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. The in t er f ace also perm it s: [ Team LiB ]

students_pkg.add_student(name,major,status,state,license_no); [ Team LiB ]

NO_OF_STUDENTS SUBPROGRAM This shou ld b e a f unct ion. The r equir ement is t o ret ur n an at t r ibut e of t he ent ir e st ud en t bod y. The f ollow ing is a fun ct ion w it h some flexibilit y . The u ser can use t h is fun ct ion t o get t he num ber of st ud en t s w ho hav e a specific m ajor , a specif ic st at us, or a com b in at ion. Th e t w o p ar amet er s passed w ould be ( 1 ) t h e subj ect m ajor d escrip t ion v alue f r om t he MAJOR_LOOKUP t able an d ( 2) a st at us v alue of " D eg ree" or " Cert if icat e. "

•FUNCTION NO_OF_STUDENTS Table of Content s (v_major Pr ogr am m ing IN Or a clmajor_lookup.major_desc%TYPE e ® Tr i gger s and Stor e d P roce dure s, Thir d DEFAULT Edi ti on NULL, v_status IN students.status%TYPE DEFAULT NULL) By Kevin Owens RETURN NUMBER; Pub lish er: Prent ice Hall PTR

This in t er f ace p er m it s t h e packag e user t o wr it e t h e follow ing calls: Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

-- get the number of students with an undeclared major. undeclared_major_count INTEGER :=dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Ef fect ively creat e an d man age com plex students_pkg.no_of_students(v_major=> Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o'Undeclared t h e St r uct ur ed'); Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. -- get the total number of students. Using easy- t o- follow inst r uct an d ex am ples, t his book pr esent s t echniq ues t o t ake student_count INTEGER :=ions students_pkg.no_of_students(); adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o number incor por of at e degree-seeking bu siness r ules w hich ar e easy t o man age and m odif y as t he -get the biology students. biology_degrees INTEGER :=ed include: bu sin ess evolv es. Topics cov er students_pkg.no_of_students (v_major => 'Biology', View inv_status g const r aint t h e dat a dict ion ar y =>s in 'Degree'); Com plex r ule enf orcem en t The STATUS colum n indicat es t he st u dent ' s st at us w it h t he school and has a CHECK PL/ SQL p r ogr am un it s and langu age f eat u res const r ain t w it h v alid v alues of " Degr ee" and " Cer t ificat e." Dat a t y pes and comp osit e st r u ct u re

PACKAGE SPECIFICATION Er r or han dling and except ions nt er - pr comion munow nicatdions The pIackag e ocess sp ecificat ef ines t he in t erf aces. I t in it ially ap pears t o m eet t he r eq uir em ent s of ad ding a st u dent and ret u rn ing a count of st ud en t s in t he school. This is a Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch st ar t ing point . We can ad d su bpr ogr am s as n eeded. Ad dit ional pr ocedu res an d f un ct ion s can m or e enhan ce t he ov er all f un ct ion alit y of t he pack age. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] CREATE OR REPLACE PACKAGE students_pkg IS PROCEDURE add_student (v_student_name IN students.student_name%TYPE, v_college_major IN students.college_major%TYPE,

[ Teamv_status LiB ] v_state v_license_no

IN IN IN

students.status%TYPE, students.state%TYPE DEFAULT NULL, students.license_no%TYPE DEFAULT NULL);

FUNCTION NO_OF_STUDENTS (v_major IN major_lookup.major_desc%TYPE DEFAULT NULL, v_status IN students.status%TYPE DEFAULT NULL) RETURN NUMBER; END students_pkg;

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

10.5 Package Body The f ollow in g is t he bod y for t he st ud en t 's packag e. I t includes j ust p rocedur e code for t h e insert and a select for a st udent count . This code cou ld b e en hanced wit h er ror hand lin g log ic; for ex am ple, it should include except ion- h andling logic f or t h e case w h er e t h e V_STATUS par am et er violat es t he CHECK const r ain t ( r efer t o pp . 103 –10 4 for CHECK con st r aint except ion hand lin g. )



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

CREATE OR REPLACE PACKAGE BODY students_pkg IS By Kevin Owens PROCEDURE add_student (v_student_name IN students.student_name%TYPE, v_college_major IN students.college_major%TYPE, Pub lish er: Prent ice Hall PTR v_status IN students.status%TYPE, Pub Dat e: Decem ber 0 5, 2 003 v_state IN students.state%TYPE DEFAULT NULL, I SBN: 0- 13 -0 850 33 -0 v_license_no IN students.license_no%TYPE DEFAULT NULL) IS Pages: 44 8 BEGIN INSERT INTO students VALUES ('A'||students_pk_seq.NEXTVAL, Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t v_student_name, Kevin Ow ensv_college_major, ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you v_status, w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. v_state, Using easy- tv_license_no); o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our END add_student; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu FUNCTION sin ess evolv es. Topics cov er ed include: NO_OF_STUDENTS (v_major IN major_lookup.major_desc%TYPE DEFAULT NULL, v_status IN students.status%TYPE DEFAULT NULL) View in g const r aint s in t h e dat a dict ion ar y RETURN NUMBER IS Com plex r ule enf orcem en t ccount INTEGER; BEGIN PL/ SQL p r ogr am un it s and langu age f eat u res SELECT COUNT (*) INTO ccount FROM major_lookup Dat a t y pesstudents, and comp osit e st r u ct u re WHERE students.college_major = major_lookup.major major_lookup.major_desc = Er AND r or han dling and except ions nvl(v_major,major_lookup.major_desc) I ntAND er - pr ocess com mu nicat ions students.status = nvl(v_status,students.status); RETURN ccount; at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch ENDDeclar NO_OF_STUDENTS; m or e END students_pkg; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for abase evtelopers, d esign er s, andt opr leader look in g tan o bd uild anions. d m aint ain ar t re uly Thedat d ev elopmden of t h e bod y can lead otoj h ect er local p rsocedu res f unct Th ese int ellig en t , com plex dat abases. hidd en , also called pr iv at e. Consider t h e st ru ct u r e of t he st ud en t 's packag e body , w h ich is show n next . The n ot at ion in t h e packag e bod y, declar at ive p ar t , ident if ies t he r egion wer e w e [can Team LiB ] declare v ar iables global t o all p rocedur es in t he b ody . I n t his r eg ion w e can opt ionally declare t yp es, ex cept ion s, and pr oced ur es—ev er y t hing in t his r egion is local t o t h e packag e bod y, yet global t o all pr ocedur es declar ed beneat h it .

[ Team LiB ]

PACKAGE BODY students_pkg IS Declarative part. PROCEDURE add_student( etc, ) END; FUNCTION no_of_student( etc, ) END; END students_pkg;

Ther e ar e t w o op t ions w hen addin g local sub pr ogr am s t o t he declarat iv e par t . One is t o code am bofodies sequ •t he su bpr ogrTable Content s en t ially ; how ever , t her e can be no for w ar d r efer encin g amon g t he bpr ogrOr am Consider local p rocedur es.ti The Pr ogrsu am m ing a cl eb®odies. Tr i gger s and Stortew d oP roce dure s, Thir d Edi on b ody look s like t his. By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 PACKAGE BODY students_pkg IS I SBN: 0- 13 -0 850 33 -0 ( etc, ) IS PROCEDURE local_1 Pages: 44 8 BEGIN body code END; PROCEDURE local_2 ( etc, ) IS BEGIN Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t code Kevin Owbody ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches END;you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. PROCEDURE add_student( etc, ) IS Using easyt o- code follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake body adv END; ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules) wRETURN hich ar eetc easyISt o man age and m odif y as t he FUNCTION no_of_student( etc, bu sin essbody evolv code es. Topics cov er ed include: END; END students_pkg; View in g const r aint s in t h e dat a dict ion ar y

Com plex r ule enf orcem en t I n t his pack age b ody , ADD_ STUDENT and NO_ OF_STUDENTS can r ef erence LOCAL_ 1 and LOCAL_ Thep rpr ocedu re itLOCAL_2 canage r efer ence PL/2. SQL ogr am un s and langu f eat u resLOCAL_1 bu t LOCAL_ 1 can not refer ence LOCAL_ 2—t he com piler , at t he t im e it com piles LOCAL_1 , has n o k now n declar at ion of LOCAL_ Dat2.a t y pes and comp osit e st r u ct u re The stEr y le t hedling pr eceding pack age r orofhan and except ions is m ost com m on. Local pr ocedu r es f r eq uent ly exist at t h e t op of t he p ackag e. Th er e is u su ally not mu ch int er depend en cy am on g local p rocedur es in a bod y.I nt Aneralt nat iv ecom is tmu o fir st declar - prerocess nicat ions e t he defin it ion of local pr ocedur es ( called an ear ly declarat ion ) , t hen t he b ody . This code w ould look lik e t he follow in g: Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int PACKAGE ellig en tBODY , com plex students_pkg dat abases. IS [ Team LiB ] PROCEDURE local_1 ( etc, ); PROCEDURE local_2 ( etc, ); PROCEDURE local_1 ( etc, ) IS

BEGIN [ Team LiB ] body code END; PROCEDURE local_2 ( etc, ) IS BEGIN body code END; PROCEDURE add_student( etc, ) IS body code END; FUNCTION no_of_student( etc, ) RETURN etc IS body code END; END students_pkg; •

Table of Content s

Becau se all su bpr ogr am definit ions occur p r ior t o sub pr ogr am bod ies, an y su bpr ogr am can Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on call any ot h er su bpr ogr am . Fur t h er m or e, t he local subp rog ram bodies can be placed in any By Kevin Owens or der . For t his p ack age b ody , LOCAL_ 1 an d LOCAL_2 su bpr og ram bodies can b e placed last in t he p ack age b ody . Pub lish er: ]Prent ice [ Team LiB

Hall PTR

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

10.6 Application Partitioning Figur e 10 - 6 illust r at es a sub sy st em, also called an ap plicat ion , t h at has visible and pr iv at e pack age com ponent s. Th e cont r ast b et w een t h e w hit e an d shad ed p art denot es a packag e specif icat ion par t as dist inct f r om a p ack age body . Th e w hit e, " exp osed" slot s r ep resen t com ponent s of an API . Th e API defin es t he int er face and , in general, sp ecifies w hat t he pack age d oes. Th e body is t he im plement at ion . To see t h e imp lem ent at ion ( i. e. , h ow t he cod e per for m s it s t ask ) , one mu st look at t he pack age code.



Figu r e 1 0 -6 . Booch D ia gr a m : Sub sy st em w i t h Pack age s a nd St an dAl one Pr ogr a m s. Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ases t of o incor por at e bu siness hich garf e o man and mpon odifen y as he Theab d esign a sy st em begins w it hr ules par t itwionin uneasy ct iontalit y in tage o sub com t s, tor bu sin ess evolv es. pr Topics erinu ed es include: subsy st em s. The ocess cov cont w it h par t it ionin g t he subsy st em in t o p ack ages. A sing le pack age w it hin a su bsyst em sat isf ies a set of r elat ed r eq uir em ent s. A su bsyst em w ill likely include Or acle b uilt - in p ack ages ( e. g. , UTL_ FI LE f or File I O) . A p ack age can logically r esid e in View in g const r aint s in t h e dat a dict ion ar y m ult iple sub sy st ems, also called ap plicat ion s. Com plex r ule enf orcem en t We can imp lem ent t he concept of a subsy st em using t he ex ist ing d at abase fr am ewor k , specif ically t h e dat ab ase schem a. To m ak e a su bsyst em , w e can encapsu lat e packag es as PL/ SQL p r ogr am un it s and langu age f eat u res obj ect s wit h in a sch em a and use dat ab ase g r ant s t o m ake som e pack ages v isible an d som e not . The ages, w hich ran t s, become t he API of t h e subsy st em . A Dat ap ack t y pes andforcomp ositweestgrave u ct ugre pr ogr am m er mig ht develop a usefu l and gener al pu rp ose dat es pack age t h at w ould exist in nu merErous st ems. r or sub hansy dling and except ions Figur eI nt 10 r atcom es amu sub sy stions em for a St u dent Reg ist r at ion App licat ion. I n cont ains a set er- -7prillust ocess nicat of pack ages t hat supp ort all t h e fu nct ionalit y for st u dent regist r at ion. One pack age is exp osed. This h e API . I t s, pr including ov ides ADD and at ionsf or oneign t he kpr iv at d at, aand st ormed in Declar at ivise tconst r aint p rim ar yGET k eyoper , u nique, ey, cheeck uch t he t ables m or e of t he schem a and sup por t s ot her ap plicat ion code t h at r equir es t hese ser v ices. For exam ple, a st udent housing app licat ion m ight r eq uir e t he GET serv ice comp onent of t he API . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase esignterIs, pra ojtect s look g t o b uild an d of m aint ainert rauly Figu r e d1ev 0 elopers, -7 . St udden n fand or m i onleader Sy st em inConsi st i ng Sev l int ellig en t , com plex dat abases.

Ap pli ca t ion s.

[ Team LiB ]

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Figur By Kevin e 10 Owens - 7 is dr awn t o illu st rat e how ap plicat ion s w it hin a single d at abase can b e par t it ioned and how t he log ic wit h in p art it ion s can in t er conn ect t hr ough an API . This d iag r am show s a single d at abase. Applicat ion can easily be dist rib ut ed am on g sever al d at abases and ach iev e lisheer: Prentof ice in Hall t he Pub sam level t erPTR conn ect iv it y using dat abase link s. Pub Dat e: Decem ber 0 5, 2 003

The St udent Regist r at ion Ap plicat ion ( see Figur e 10 - 7) sh ows t hr ee packag es t hat are not I SBN: 0- 13 -0 850 33 -0 par t of t he v isib le API . These are n ot callable f rom ot her app licat ions. Th e applicat ion, as Pages: 44 8 dr aw n lit er ally, con sist s of f our p ack ages an d f our t ab les. One pack age is v isib le. We g ran t ex ecut e pr ivileges t o u ser s w ho need t h e API . Once t h e app licat ion becom es pr odu ct ion , w e can fur t h er lock - dow n t he schem a and r evok e CREATE TABLE and similar Ef fect fively e an dr atman comion plexsch dat abases w itah dOr st ems abinase exesper t r oles r om tcreat he regist ion age pr oduct em a. Fr om atacle! abaseSyper spectand iv e, dat t his clud t he Kevin Ow:ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d follow ing t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. UsingCr easyinstaccount r uct ionsfor an dt he exst am his book esent s t echniq ues t o St t ake eat et oa dfollow at abase udples, en t rtegist rat ionprschema. We call t his u dent adv ant ag e of acle feat urion es such Regist r atOr ion Ap plicat ( SRA)as . t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he t he es. ap plicat ioncov . Crereat all t ab les an d p ack ages in t he SRA schema. bu sin Build ess evolv Topics edeinclude: GRANT EXECUTE ON API pack ages t o ot her users su ch as t h e St ud en t Housing Viewlicat in g ion const aint s in t h e dat a dict ion ar y App owr ner. Comoke plext he r ule orcem en t Rev Orenf acle CONNECT an d RESOURCE r oles fr om t h e SRA. Th is pr ev ent s accid en t al up dat es t o pr oduct ion by d ev elop m en t an d t est t eam s t h at w or k on sep arat e PL/ p r ogr am it s dat andabase languinst ageances. f eat u res devSQL elop ment and un t est Dat r uwctay u reaccess t o t h e SRA sy st em . Th is is t he p ack age or set Theraet yispes nowand a rcomp est r ictosit ed eonsteof pack ages t hat for m t he API . Er r or han dling and except ions The ap plicat ion w ill un der go enh ancem ent s and new r eleases. Th is w ill requ ire enab lin g It he nt erapplicat - pr ocess mu nicat ions and RESOURCE, and ot her r oles t o p er m it d at abase ioncom r oles, CONNECT t able an d PL/ SQL enhan cem ent s. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e [ Team LiB ] Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

10.7 Data Abstraction You can sim plify com plex applicat ion log ic by b uilding abst r act st r uct ur es on t op of t he exist ing langu age st r uct ur es. The f ollow ing p ack age im plem en t s a STACK b uilt using a PL/ SQL in dex- b y t able. This is a last - in- fir st - out ( LI FO) st ack of st ud en t n ames. This dem onst r at es t he ab ilit y t o bin d d at a an d op er at ions t oget her and r est r ict t he int er face t o t he defin it ion s in t he p ack age specificat ion. The u ser of t his pack age m ust con for m t o t he p ush/ pop oper at ions in t he sp ecificat ion. Alt hou gh t he p ack age b ody im plem en t s t his st r uct ur e w it h an index - by t ab le, t he im plem ent at ion could be a dat ab ase t able, a set of t ab les, or t ab les in anot her dat ab ase—t h is •uses a PL/ SQL Table of Content s t able. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

The st ack p ack age h as t he follow in g operat ion s and except ions: By Kevin Owens Su ogPrent ra mice Pubbpr lish er:

Purp ose

Hall PTR

Pub Dat e: Decem ber 0This 5, 2 003 CLEAR p rocedur e

em pt ies t he st ack .

I SBN: 0- 13 -0 850 33 -0

PUSH Pages: POP

44 8

This p ushes a n am e ont o t he st ack. This is ov er load ed . You can u se t he f unct ion t o p op a nam e. You can also use t h e pr oced ur e for m .

STACK_NOT_EMPTY r et ur ns TRUE t heabases st ack w h as n ames. Ef fect ively creat e an dThis man age com plexifdat it h any Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d Ex ce pt i ons t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. UNDERFLOW A p op of an em pt y st ack is an except ion, sim ilar t o su bt r act in g 1 f r om a Using easy- t o- follow POSI inst rTI uctVE ions anber d ext ham esent uesbyt ozero t akeis an n um at ples, h as at his cur book r en t vpr alue of s1 t. echniq A d ivide adv ant ag e of Or acle except feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat ion because it p rod uces a r esult not in t he set of nu mb erallow s. Wey our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he r aise t he except ion UND ERFLOW f ollow ing t h e pop of an em pt y st ack . bu sin ess evolv es. Topics cov er ed include: First , look at how one m ight use t h e st ack . We w ant an int er face t o be sim ple. The f ollowin g PL/ SQL cod st u sdent esafrdict om ion t h earSTUD ENTS t ab le and pu sh es t he nam es ont o t he View ineg select const sr aint in t hnam e dat y st ack. Follow ing t hat t he n ames ar e p oped w it h in a call t o DBMS_OUTPUT. Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re BEGIN FOR (SELECT student_name FROM students) LOOP Er r orrec hanIN dling and except ions students_stack.push(rec.student_name); I nt erLOOP; - pr ocess com mu nicat ions END Declar at iv e const r aint s, including p rim ar y k ey , LOOP u nique, f or eign k ey, ch eck , and m uch WHILE (students_stack.stack_not_empty) m or edbms_output.put_line(students_stack.pop); END LOOP; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce END; for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. Ru nning t h e PL/ SQL b lock p rod uces t he f ollow ing n ames: [ Team LiB ]

[ Team LiB ] William Steven Kathryn Mary John

The sp ecificat ion and body f or t h e st ack are show n nex t . You can easily m odify t his for a FI FO LI ST st r uct u re. Th e comp onent st or ed in t h e index - by t ab le is a VARCHAR2. You can build a st ack of STUDENT% ROWTYPE st r uct ur es.

PACKAGE students_stack IS •CREATE OR REPLACE Table of Content s -Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on -- Empties the stack. By Kevin Owens -PROCEDURE clear_stack; -Pub lish er: Prent ice Hall PTR -- Push a name onto the stack. Pub --Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 push 850 33 -0(name IN students.student_name%TYPE); PROCEDURE Pages: 44 8 --- Pop and return a name from the stack. -PROCEDURE pop (name OUT students.student_name%TYPE); students.student_name%TYPE; Ef fectFUNCTION ively creatpop e an dRETURN man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin-Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d -- you Check status. Return true if stack t eaches w hat y ou n eed t o kn ow t o build rob usthas an d data com plex dat ab ases f or y our b usiness. -stack_not_empty BOOLEAN; UsingFUNCTION easy- t o- follow inst r uct ions anRETURN d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our This exception issiness raised a ar pop dat ab-ases t o incor por at e bu r uleswith w hich e easy t o man age and m odif y as t he anes. empty stack. bu sin-esson evolv Topics cov er ed include: -UNDERFLOW exception; View in g const r aint s in t h e dat a dict ion ar y END students_stack; Com plex r ule enf orcem en t SQL r ogr am langu age f eat The pPL/ ackag e pbody f or tun h isit sstand ack encapsulat es tuhres e st ack t hat is imp lem ent ed as a PL/ SQL index - by t able. Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions CREATE OR at REPLACE BODY students_stack IS f or eign k ey, ch eck , and m uch Declar iv e constPACKAGE r aint s, including p rim ar y k ey , u nique, TYPE table_type IS TABLE OF students.student_name%TYPE m or e INDEX BY BINARY_INTEGER; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce the_stack table_type; for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. stack_pointer BINARY_INTEGER := 0; [ Team LiB ] PROCEDURE clear_stack IS BEGIN stack_pointer := 0;

ENDLiB clear_stack; [ Team ] PROCEDURE push (name IN students.student_name%TYPE) IS BEGIN stack_pointer := stack_pointer +1; the_stack(stack_pointer) := name; END push; PROCEDURE pop (name OUT students.student_name%TYPE) IS BEGIN name := the_stack(stack_pointer); stack_pointer := stack_pointer—1; EXCEPTION WHEN NO_DATA_FOUND THEN RAISE underflow; END pop; •

Table of Content s

FUNCTION pop RETURN students.student_name%TYPE IS BEGIN By Kevin Owens stack_pointer := stack_pointer—1; RETURN the_stack(stack_pointer + 1); EXCEPTION Pub lish er: Prent ice Hall PTR WHEN NO_DATA_FOUND THEN Pub Dat e: Decem ber 0 5, 2 003 stack_pointer := stack_pointer + 1; I SBN: 0- 13RAISE -0 850 33 -0 underflow; END pop; Pages: 44 8 Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

FUNCTION stack_not_empty RETURN BOOLEAN IS BEGIN (stack_pointer > 0); Ef fect ivelyRETURN creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t stack_not_empty; KevinEND Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d END students_stack; t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake [adv Team LiB ] Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our ant ag e of dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

10.8 Parameters and Modes Pr ocedu r es ar e sub pr ogr am s t hat gener ally perf or m some ser vice—t hey act on or chan ge som et h in g. A fu nct ion g en er ally j ust r et ur ns inf or m at ion . All sub pr ogr am par am et er s h ave a m ode t h at is sy nt act ically coded bet w een t h e var iable an d t he t y pe d ef init ion. PL/ SQL pr ogr am s hav e t h r ee m odes: I N ( d ef ault ) I N OUT •

Table of Content s

OUT Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

An I N m ode p aram et er is passed t o a sub pr ogr am w it h t he u nder st an ding t hat t h e subp rog r am uses t he p aram et er as a con st an t , r ead- only v alue. A par amet er p assed Pub lish er: Prent ice Hall PTR w it h I N m ode can be a lit er al exp r ession, const ant declar at ion , or v ariab le declar at ion. Pub Dat e: Decem ber 0 5, 2 003 I n t he case of a v ar iab le, t his m ode p rov ides som e m easur e of secu rit y on t h e par t of SBN:calling 0- 13 -0 850 33 -0am . Th e caller k now s t h at up on com plet ion of t he call, t he var iable is tIhe pr ogr Pages: 44 8 un ch anged. The com piler en for ces t h is secur it y . Ther e ar e t w o checks. Fir st , if t he com piler d et ect s an I N m ode par amet er t o t he left of an assign ment , t he com pile f ails. Secon d, if t h e var iable is p assed t o a su bseq uent pr ocedu r e t hat uses it as an OUT or I N OUT p ar amet er , t he com pile f ails. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t IN Par am et er s passed in t his m ode can only b e v ariab les, not lit er als or con st an t s. The Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d OUT assu m pt ion is t hat t he called p rocedur e w ill chang e t he con t en t p assed. Th e called t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. pr oced ur e w ill r ead as w ell as w r it e t o t he st r uct ur e cont ent . An ex am ple is a pr oced urfollow e t hat inst passes a st r an ingd tex o aam dat a- scr ubbbook in g ppr r ocedu Th e scrues ub bing Using easyt or uct ions ples, t his esentre. s t echniq t o t ake r unsfeat t heurstes r ing t hras ougt rig h agers loopand ch eck ing for in valid chfaract r emovyes adv antpr agoced e ofur Oreacle such st ored pr oced ur eseat u rer ess tand hat allow our un w ant ed b yt es. Upon comp let ion of t he scr ubb ing, t he pr ocedur e t h at m ade dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t het he call hasevolv a clean st r in g. cov er ed include: bu sin ess es. Topics IN

OUT Par am et er s passed in t his m ode can only b e v ariab les, not lit er als or con st an t s. Wit hin a su bpr ogr am , t h e init ial v alu e of an OUT m ode p aram et er is NULL. Th e int ent of using View in g const r aint s in t h e dat a dict ion ar y an OUT m ode p aram et er is t o con vey som et hing about t he in t erf ace—t h e caller h as no obligat t o enf pass dat a. called pr oced ur e can wr it e t o t he dat a st r uct u re; it can Com plexion r ule orcem enThe t r ead t h e st ru ct ur e. For ex am ple, a sor t p rocedu re m igh t b e passed as an OUT m ode st rSQL uct urpe. The of sor t ingage r equir an it er at iv e pr ocess of r ead/ w r it e operat ion s. PL/ r ogr amp rocess un it s and langu f eates u res The called p rocedur e on ly reads t he st r uct ur e t o per for m t h e sor t . Any OUT m od e paraam er and can comp changosit e to I Nr uOUT Dat t y et pes e st ct u rew it hou t any im p act . Howev er, t his m ay not be consist ent w it h t he or iginal desig n. I f par am et er s ar bit r ar ily ch ange f r om OUT t o I N ErOUT, r or han except t h isdling misr and ep resent s tions h e pr ogr am int er face an d conf uses t he p r ogr amm er w ho w ond er s, " What dat a is supp osed t o be passed ?" I nt er - pr ocess com mu nicat ions Declar iv e const r aint s, including p rim ar y k ey , u nique, f or eign 10.8.1 INatMode (Default) is a Constant

k ey, ch eck , and m uch

m or e

An I N m ode p aram et er is a const an t or m ust be t r eat ed as a const ant . A pr ocedur e t h at Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce accept s an I N m ode ar gum ent is r est r ict ed f rom wr it ing t o t hat ar gum ent . Th e follow ing for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly pr oced ur e w ill not comp ile becau se line 3 w r it es t o t he I N m ode var iable. int ellig en t , com plex dat abases. [ Team LiB ]

1

PROCEDURE print_next_value(v_data IN INTEGER) IS

2 BEGIN [ Team LiB ] 3 v_data := v_data+1; -- compile error 4 dbms_output.put_line(v_data); 5 END;

The f ollow in g p r ocedu re, w h ich per for m s t he sam e serv ice, does com p ile. Th e con st ant can be in an exp ression . This is t h e corr ect use of an I N m ode par amet er .

1 2 3 •4

PROCEDURE print_next_value(v_data IN INTEGER) IS BEGIN dbms_output.put_line(v_data+1); Table of Content s END;

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

I n t he f ollow ing PL/ SQL block, all calls t o t he p r ev ious PRI NT_ NEXT_VALUE are valid. Line 7 , in t he PL/ SQL block, passes a var iable. Follow ing t h e call t o PRI NT_ NEXT_VALUE, t he b lock r et ain t he v alu Pubslish er: origin Prent icealHall PTRe of MY_D ATA. The au t hor of t h e pr int pr oced ur e declar es t he mod e as I Pub N, w hich inforber m s0 5,user Dat e: Decem 2 003s, " I w ill not ch ange you r dat a. " I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

1 DECLARE Ef fect ively creat e an d manINTEGER age com := plex0; dat abases w it h Or acle! Sy st ems and dat ab ase ex per t 2 zero CONSTANT Kevin Owmy_data ens ex plor es PL/ SQL, 3 INTEGER := Or 2;acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t4eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. BEGIN 5 print_next_value( 123 ); Using easyt o- follow inst r uct ions an d);ex am ples, t his book pr esent s t echniq ues t o t ake 6 print_next_value( zero adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 7 print_next_value( my_data ); dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he 8 END; bu sin ess evolv es. Topics cov er ed include: ViewIN in gOUT const Mode r aint s in 10.8.2

t h e dat a dict ion ar y

Com plex r ule enf orcem en t Ther e is an assu mp t ion d raw n f rom looking at a p rocedur e t h at t ak es an I N OUT m ode par amPL/ et er . Thp at assum ptition is t hat t he caller mres ust p rov ide d at a. Th is wou ld b e t he I N par t of SQL r ogr am un s and langu age f eat u an I N OUT ar gu ment . The f ollowin g p rocedur e, on line 4, r ead s fr om an d w r it es t o t he dat a passed . This p aram er m ust OUT. Dat a t y pes andetcomp ositbeestI rNu ct u re I t t ru ly m odifies t he dat a p assed. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions 1 PROCEDURE OUT IS f or eign k ey, ch eck , and m uch Declar at iv echange_data(v_data const r aint s, including IN p rim ar y INTEGER) k ey , u nique, 2 BEGIN m or e 3 for i in 1..10 loop Pr ogr am m ing v_data Oracle Tr igger s and +St or 4 := v_data 1;ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly 5 dat abase end dloop; int en t , com plex dat abases. 6 ellig END; [ Team LiB ] The caller of CHANGE_ DATA k now s t hat t he bef ore an d aft er v alues of t he I N OUT par am et er m ay dif fer .

MY_ DATA bef ore t he call is 0. [ Team LiB ] The v alue of MY_DATA aft er t h e block ex ecut ion is 10.

1 2 3 4 5 6

DECLARE my_data INTEGER := 0; BEGIN print_data(my_data); dbms_output.put_line('block print: '||my_data); END;

•I f t his PL/ SQL Table of Content block declarses MY_D ATA as a con st ant , b lock ex ecut ion f ails. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

10.8.3 OUT Mode Pub lish er: Prent ice Hall PTR

OUT m ode par amet er s conv ey cr it ical infor m at ion about t he in t erf ace. Th e int ent is t hat t he Pub Dat e: Decem ber 0 5, 2 003 caller h as no obligat ion t o p rov ide cont en t t o t he caller . An OUT mod e v ariable, u pon en t r y t o I SBN: 0- 13 -0 850 33 -0 t he pr ocedu re, is NULL. Pages: 44 8

I n t he f ollow ing pr ocedur e, pr ior t o t he ex ecut ion of line 4 , V_DATA is NULL. A v alu e of 100 is assig ned. Du r in g ex ecu t ion, t h e pr oced ur e r ead s and w rit es t o t he par amet er . From t he beginn ing of pr ogr am logic, PROVI D E_D ATA m akes n o assum pt ion about t he con t en t of V_D ATA. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 1 PROCEDURE provide_data(v_data INTEGER) dat ab ases t o incor por at e bu siness r ules OUT w hich ar e easy t o man age and m odif y as t he 2 ISess evolv es. Topics cov er ed include: bu sin 3 BEGIN 4 v_data := 100; View in g iconst aint s inLOOP t h e dat a dict ion ar y 5 FOR IN r1..10 6 v_data := v_data +1; Com plexLOOP; r ule enf orcem en t 7 END 8 END; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re A u ser of PROVI DE_D ATA is t h e follow ing PL/ SQL b lock . The fir st I NSERT int o TEMP w ill b e t he value 0. Th e second inser t w ill be t h e valu e 110 . Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e 1 DECLARE 2 my_data INTEGER 0; St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Pr ogr am m ing Oracle Tr igger:= s and 3 BEGIN for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly 4 ellig eninsert into values (my_data); int t , com plex dattemp abases. 5 provide_data(my_data); 6 insert into temp values (my_data); [ Team LiB ] 7 END;

[ Team LiB ] 10.8.4 Functions and Modes The d ef ault m ode for pr oced ur es an d fun ct ion s is I N m ode. A general pr act ice, t o m ake code clear er, is t o alw ay s t y pe t h e m ode, even w hen u sin g t he def ault . The con vent ion w it h a fu nct ion is t hat t hey ar e select ors—t h ey ret ur n a specific p iece of inf orm at ion. They also per for m a pr ocessing- t y pe ser vice w her e dat a is passed in, ch anged, an d ret ur n ed w it h an I N OUT m ode arg um en t . Exam ples ar e bu ilt - in st r ing fun ct ion s: REPLACE and TRANSLATE. Funct ions are of t en nam ed using a noun ; pr ocedur es ar e nam ed w it h a ver b. Th e larg e per cent age of f unct ions in any ap plicat ion w ill hav e all ar g um en t s passed w it h t he I N mod e, bu t f unct ions can be declar ed w it h par am et er s t h at h ave all t hr ee m odes. Fu nct ions w it h par am et er s ot h er t han I N m ode shou ld b e r are. The u se of OUT m ode ar gu ment s w it h a fu nct ion p r ovides a t ech nique for som e simp le int er faces, especially w h en t h e fun ct ion t r uly is a select or bu t m ust pr ovid e dual pieces of A f unct ion desig •inf orm at ion. Table of Content s n can r eq uir e t hat it f et ch a recor d, bu t also r et ur ns t he success of ogr t hat ch.OrCert ain a pr ocedur accom his,ti on but it m ay b e desir able, f rom an API Pr am fet m ing a cl e ® Trly i gger s and Store e dcan P roce dure s,plish Thir d t Edi per sp ect iv e, t o p rov ide a fu nct ion t hat follow s t his d esign . By Kevin Owens The d ecision of f unct ion or p rocedur e shou ld , f orem ost , consid er t he r eadabilit y an d sim plicit y of t he cod e t hat w ill use t his in t er f ace. Th e follow ing illu st r at es a fun ct ion d esign t hat r et ur ns Pub lish er: Prent ice Hall PTR dat a plus a st at us. For t h is int erf ace, assum e ARG_1 is a p r im ar y k ey value used t o ident ify Pub Dat e: Decem ber 0 5, 2 003 t he pr ecise r ecor d t o f et ch. The ar gu ment NEXT_ REC is t he wan t ed d at a. I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

FUNCTION IN com type, Ef fect ively next_rec(arg1 creat e an d man age plexnext_record dat abases w itOUT h Or type) acle! Sy st ems and dat ab ase ex per t RETURN Kevin OwBOOLEAN; ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. This s t heinst u ser w r itan e dcod asples, f ollow s: book pr esent s t echniq ues t o t ake Usingd esign easy- tallow o- follow r uctt oions exeam t his adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: WHILEView (next_rec(arg1, in g const r aint s inmy_record_structure)) t h e dat a dict ion ar y LOOP Com plex my_record_structure; r ule enf orcem en t process END LOOP; PL/ SQL p r ogr am un it s and langu age f eat u res a tiv y pes ositNEXT_ e st r u ctREC u re is a p r ocedu re. Th e pr oced ur e solu t ion w ou ld b e t he An altDat er nat e t o and t he comp f un ct ion follow ing —w e renam e t he subp rog r am w it h a v er b. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e PROCEDURE get_next_rec(arg1 IN type, next_record OUT type, Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce status OUT BOOLEAN); for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. From ser]'s p er spect ive, w e can use t his p r ocedu re as w ell—a sligh t ly diff er ent int er face. [ Teama uLiB The cod e block st ill uses a loop t o f et ch all r ecor ds.

[ Team LiB ] LOOP get_next_rec(arg1, my_record_structure, status) EXIT WHEN NOT status; process my_record_structure; END LOOP;

From t he PL/ SQL block per sp ect iv e, t her e is lit t le diff er ence. I n concept , t he f unct ion is a select or t hat evalu at es t o t h e next r ecor d, but opt ionally p rov ides st at us about t hat fet ch. Th e pr oced ur e behav es as a ser vice, fet ching a recor d, an d r et ur ning t h e r ecor d and a st at us.

10.8.5 Named versus Positional Notation •

Table of Content s

Con a pr ei gger w it hs tand he Stor f ollow int er face init ion. Pr ogrsider am m ing Oroced a cl e ®urTr e d ing P roce dure s, ThirddefEdi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 PROCEDURE proc_name (arg1 mode and type, arg2 mode and type); I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

A u ser h as t w o sy nt ax op t ions. The f ir st is POSI TI ONAL not at ion, t he secon d is NAMED not at ion : Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 1. proc_name(variable_1, variable_2); Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 2. proc_name(arg1 => ur variable_1, arg2 adv ant ag e of Or acle feat es such as t rig gers => andvariable_2); st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: What does t h e t erm For m al Par am et er Nam e r efer t o? The f or mal par am et er n ame ref er s t o t he nam e used in t he in t erf ace definit ion of t he pr ocedu re or fu nct ion. For t h e pr eceding pr oced ur e,inPROC_NAME, t het hf e orm View g const r aint s in datala par dictamet ion arery n ames ar e ARG1 an d ARG2. Form al parplex amet er nam es shou Com r ule enf orcem en ld t be generic an d st ill conv ey w hat t he p aram et er is used for . The f ollow in g p r ocedu re definit ion uses for m al nam es t hat conv ey t o t h e user t he in t en t of SQLetper—t r ogr he amf orm un it al s and langu f eat res each PL/ p aram p aram et erage nam esuar e FI LE_I D and RECORD _READ : Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - prget_record ocess com mu nicat ions PROCEDURE (file_id IN INTEGER, record_read OUT VARCHAR2); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e On e can look at t his p rocedur e d ef init ion and be f airly cert ain h ow t o u se t his code. Add it ional Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce inf orm at ion m ay be in clud ed in t he p r ocedu re or packag e docum ent at ion . The u ser of t h is for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly pr oced ur e has t w o callin g st y les. Th e fir st is p osit ion al not at ion . int ellig en t , com plex dat abases. [ Team LiB ]

DECLARE

file_id INTEGER; [ Team LiB ] next_payroll_record VARCHAR2(100); BEGIN get_record(file_id, next_payroll_record); END;

I s t his PL/ SQL block clear —as f ar as w hat t he cod e does? The PL/ SQL block uses v ariab le nam es t hat conv ey t heir use—t his m ak es it fair ly clear w h at is h appening in t his code. Th e PL/ SQL b lock can use n amed not at ion , show n next :



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on DECLARE

file_id By Kevin Owens

INTEGER; next_payroll_record VARCHAR2(100); BEGIN Pub lish er: Prent ice Hall PTR

get_record Pub Dat e: Decem ber 0 5, 2 003 (file_id => I SBN: 0- 13 -0 850 33 -0

file_id, record_read => next_payroll_record); Pages: 44 8 END; an d er? manThe agecall comt oplex datRECORD abases wisitcorr h Orect acle! st ems andatdat IEfs fect t hisively b lockcreat an ye clear GET_ bu Sy t t he inf orm ionab isase ex per t Kevin ex plor es SQL, Or acle's answnam er t oes, t h for e St uctpur ed Query Langu , an d r ed undOw antens . Because of PL/ w ellchosen var iable mral aram et er not at ionage , in (t SQL) his case, tiseaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. not necessar y and, t o m ost r eader s, mak es t he cod e w ord y and m or e diff icu lt t o read. When do you u se n am ed not at ion ? Th er e ar e sev er al cases w hen nam ed not at ion is usef ul. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat asesn tam o incor por e bu siness w hich ar eeseasy o oose man age m odif y ely as tconv he ey ed not atat ion w hen t her ules var iable nam y ou tch do nand ot com plet 1 .abUse bu sin tess ed m include: heirevolv u se.es. ForTopics exam pcov le, er y ou ay pass a lit er al v alue and u se n am ed not at ion as a code docum ent at ion t ool. Viewninam g const r aint s in t h e dat y is coded w it h default valu es and you ar e only 2 . Use ed not at ion w hen t heasudict bprion ograram using som e of t he d ef ault s. Com plex r ule enf orcem en t The f ir st condit ion, passin g a lit er al in a pr ocedu re, can occu r w it h I N mod e par am et er s. I t PL/ SQL p r ogr am un it s and langu age f eat u res m ay not be clear w hat t he lit eral is used f or . This is m or e likely t o occur w hen y our cod e int er faces w it h p ack ages t h at ar e ou t sid e t he p resent schem a. Ex am ples ar e ot her Dat a t y pes and comp osit e st r u ct u re app licat ions and Or acle p ack ages. The follow in g is a PL/ SQL block t hat su bm it s a j ob t o t h e Or acle This block will d isp at ch a r eq uest t o t he j ob q ueue. The r equest is ErDBMS_JOB r or han dlingpack andage. except ions t o ru n, asy nchr onously , t he st or ed pr ocedu r e PROCESS_DATA. Th e pr ogr am PROCESS_ DATA w ill r un encom t of mu t h enicat caller . I t s execut ion does not block t he caller. The f ollow ing is I nt independ er - pr ocess ions corr ect b ut t he dev elop er sh ould con sider n amed not at ion as a m ean s t o clearif y t he dat a passed . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. DECLARE [ Team id LiB BINARY_INTEGER; ] BEGIN dbms_job.submit(id, 'process_data;', SYSDATE); END;

[ Team LiB ] Ev en a dev eloper f am iliar w it h t h e DBMS_JOB pack age w ou ld lik e t o see a f ew for m al par am et er nam es in t h is case. The last ar gum ent is a bu ilt - in f unct ion, SYSDATE, an d som eon e less f amiliar w it h DBMS_JOB m igh t w ant t o look at t h is cod e t o see w hat t his d at a m ean s. The u se of f or mal nam es m akes t h e pr oced ur e call sligh t ly m ore readab le.

DECLARE id integer; BEGIN dbms_job.submit(job => id, what => 'process_data;', next_date=> SYSDATE); END; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens Use n am ed not at ion w hen y ou w an t t o pick and choose specif ic par am et er s t o pass—sk ippin g som e for m al par am et er s f or w her e t her e is a d ef ault valu e. ( Def ault par am et er s ar e cover ed in Sect ion 10 . 8. 6, " D ef ault Param et ers. " Pub lish er: Prent ice Hall PTR

ConPub sider follow oced ur e t hat com put es an agg regat e salar y . This sub pr ogr am Datte:he Decem ber ing 0 5, 2pr 003 includes d ef0ault alues I SBN: 13 -0v850 33 -0 f or each par am et er : MONTHLY_ BASE an d NO_OF_MONTHS. Calling t he AGGREGATE_SALARY f un ct ion w it h defau lt v alu es ret u rn s t he com pu t ed salar y: 10, 0 00 Pages: 44 8 t im es 12.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tCREATE eaches you w hat y ou FUNCTION n eed t o knaggregate_salary ow t o build rob ust an d com plex dat ab ases f or y our b usiness. OR REPLACE (monthly_base NUMBER := 10000, Using no_of_months easy- t o- follow instINTEGER r uct ions an ex amRETURN ples, t his book pr esent s t echniq ues t o t ake :=d 12) NUMBER adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our IS dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he BEGIN bu sinreturn ess evolv(monthly_base es. Topics cov er*edno_of_months); include: END; View in g const r aint s in t h e dat a dict ion ar y To cod e wplex it h t hr eule defau lt f or NO_OF_ MONTHS, w r it e t he f ollow in g: Com enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re DECLARE Er r or han dling and except ions monthly_base NUMBER := 9000; aggregate I nt er - pr ocess com NUMBER; mu nicat ions BEGIN Declar at iv e for constone r aintyear. s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch -salary m or e aggregate := aggregate_salary(monthly_base); END; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int en t , com abases. Youellig cannot use plex positdat ional n ot at ion and call t his pr ocedur e using t h e defau lt for MONTHLY_BASE and st ill pass t he n um ber of m ont h s. The nu m ber of m ont hs passed w ould [beTeam ] int erp r et ed as a mon t hly base an d t he r esult w ould be, f or t he salar y, t w ice t h e p osit LiB ion al, nu mb er of mon t hs. Usin g d ef ault s in t h is case r equir es nam ed n ot at ion:

[ Team LiB ] DECLARE no_of_months INTEGER := 10; aggregate NUMBER; BEGIN -- salary for 10 months. aggregate := aggregate_salary(no_of_months=>no_of_months);

10.8.6 Default Parameters A p r ocedu re or fu nct ion specificat ion can defin e a d ef ault v alue f or par am et ers t hat hav e I N or I N OUT m ode. Ther e are t w o sy nt ax f orm s illust r at ed: •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

PROCEDURE name Pub lish er: Prent ice Hall PTR (argument mode datatype := a_default_value); Pub Dat e: Decem ber 0 5, 2 003 I SBN: 013 -0 850 33 -0 PROCEDURE name Pages: 44 8 (argument mode datatype DEFAULT a_default_value);

The f ollow in g f un ct ion def in it ions each r et ur n t he ar ea of a cir cle w it h a defau lt r adius of one—t h e only difefer b et ween fun abases ct ion s iswtithe st yacle! le of Sy t h st e ems default . dat ab ase ex per t Ef fect ively creat anen d ce man age comt hese plex dat h Or and Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our FUNCTION dat ab ases tcircle o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he NUMBERcov :=er1) RETURN NUMBER IS bu sin(radius ess evolv IN es. Topics ed include: BEGIN RETURN 3.14 * radius**2; END; View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t FUNCTION circle (radius IN NUMBER DEFAULT 1) RETURN NUMBER IS BEGINPL/ SQL p r ogr am un it s and langu age f eat u res RETURN 3.14 * radius**2; END; Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions The f ollow in g PL/ SQL block cont ains four in vocat ions of t he f unct ion CI RCLE—all ar e v alid. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce DECLARE for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly radius NUMBER := 1; int ellig en t , com plex dat abases. area NUMBER; BEGIN [ Team LiB ] area := circle(); area := circle(radius); area := circle(radius+1); area := circle;

END; [ Team LiB ] When a sub pr ogr am cont ain s sev er al default par am et er s, t he user can pick and choose any of t he default s but m ay hav e t o use nam ed n ot at ion. Th e follow ing pr oced ur e upd at es a r ow in t he PROFESSOR ( DD L f or t h is t able is in Ch apt er 4) . Th is t able is:

SQL> desc professors Name Null? Type ---------------------------- -------- ----------PROF_NAME(primary key) NOT NULL VARCHAR2(10) SPECIALTY NOT NULL VARCHAR2(20) •HIRE_DATE Table of Content s NOT NULL DATE Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on SALARY NOT NULL NUMBER(5) TENURE By Kevin Owens NOT NULL VARCHAR2(3) DEPARTMENT NOT NULL VARCHAR2(10) Pub lish er: Prent ice Hall PTR

The Pub f ollow g u pdat e5,pr2 oced Dat e:inDecem ber 0 003 ur e r eq uires a pr ofessor ' s nam e—t his is t he pr im ary key . The caller can a 850 SALARY t o up dat e an d/ or a TENURE ( YES/ NO CHECK const r aint ) . I SBN:pass 0- 13 -0 33 -0 Pages: 44 8

The p ur pose of t his pr ocedu re is for a user t o u pdat e t en ur e or salar y. Th e caller p asses a t enur e v alue, passes a salar y valu e, or passes t wo v alu es—t h is upd at es bot h colum ns. The pr oced ur e r et ur ns im m ed iat ely if it is called w it h a NULL f or each p arem et er . Ef fect ively creat e an d mantage comATE plexstdat abases it ht hOr Sy st abcolum ase exnper When t he default is used, h e UPD at em en t u w ses e acle! NVL fun ctems ion t and o setdat t he to t Kevin Ow ensr ow ex plor SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t he cu rr ent colues m nPL/ v alue. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin essOR evolv es. Topics cov er ed include: CREATE REPLACE PROCEDURE update_professor (v_prof_name professors.prof_name%TYPE, v_salary professors.salary%TYPE := NULL, View in g const rprofessors.tenure%TYPE aint s in t h e dat a dict ion ar y := NULL) v_tenure IS Com plex r ule enf orcem en t BEGIN IF PL/ SQL p r ogr am un it s and langu age f eat u res v_salary IS NULL AND v_tenure IS NULL THEN Dat a t y pes and comp osit e st r u ct u re RETURN; -- nothing to change END IF; Er r or han dling and except ions UPDATE professors I nt er - pr ocess com mu nicat ions set salary = NVL(v_salary, salary), Declar attenure iv e const=r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch NVL(v_tenure, tenure) m or e prof_name = v_prof_name; WHERE END; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig encan t , com A caller u seplex p ositdat ionabases. al not at ion ex cept w hen t hey ar e using t he d ef ault for SALARY b ut w ish t o supp ly a new TENURE. The follow in g PL/ SQL block cont ains sev er al v alid ex am ples of [callin Team LiB ] g UPDATE_ PROFESSOR. The one st at ement t hat m ust use posit ional n ot at ion is on line 11 .

[ Team LiB ] 1 DECLARE 2 new_salary professors.salary%TYPE := 13000; 3 new_tenure professors.tenure%TYPE := 'YES'; 4 BEGIN 5 -- Named notation examples 6 update_professor('Blake', 12000, 'YES'); 7 update_professor('Blake', 12000); 8 update_professor('Blake', new_salary, new_tenure); 9 10 -- Positional notation examples. 11 update_professor('Blake', v_tenure => new_tenure); 12 13 update_professor('Blake', v_salary => new_salary, 14 v_tenure => new_tenure); • Table of Content s 15 Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on 16 update_professor(v_prof_name=> 'Blake', By Kevin Owens 17 v_salary => new_salary, 18 v_tenure => new_tenure); 19 END; Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 850 33 When coding pr-0 oced ur-0es and fu nct ions, place defau lt s last in t he calling sequ en ce. Th e Pages: 8 ple illu st rat es on e case t hat r equ ir es posit ional not at ion—line 11. D ef ault s pr ecedin g ex44am int er m ix ed wit h non defau lt par am et er s, or p laced lef t of n ondefau lt ar gu ment s, in cr ease t he nu mb er of scenar ios w her e t he u ser m ust cod e t o n am ed not at ion .

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin OwScaling ens ex plor Code es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 10.8.7 with Defaults t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. You enhtance t he inst f un ct ionions alit yan ofdex in ples, g cod tehis bybook add ing defausltt sechniq t o t h eues endt ooft ake a Usingcan easyo- follow r uct exist am pr esent pr oced unct ionfeat specif icat ion.as Because e defau lt s ar t o tur heesr ight ist ing code is adv ant ur agee or of fOr acle ur es such t rig gerst hand st ored preoced f eat, uall r esext hat allow y our not aff ect ed. The ex ist ing code, as w r it t en, w ill u se t he def ault v alue assigned. New code may dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he or m ay usees. t h eTopics par amcov et er New code can be w r it t en t o p ass a v alue of t he default . bu sin essn ot evolv er.ed include: Con sider t he follow ing pr oced ur e. I t u pdat es a pr ofessor record . Wit hin an app licat ion t her e could View be winide u se of t his pr oced ur e, et ion w e ar can g const r aint s in t h e dat a ydict y ex t end it f unct ionally w it hou t im pact ing exist ing code. Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re CREATE OR REPLACE PROCEDURE update_professor Er r or han dlingprofessors.prof_name%TYPE, and except ions (v_prof_name v_salary professors.salary%TYPE := NULL, I nt er - pr ocess com mu nicat ions v_tenure professors.tenure%TYPE := NULL); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m orscenar e For t his io, assum e t he pr ocedur e m ust be m odified t o sup por t em ail not if icat ion . To im plem ent t his w e ad d a par am et er , V_ NOTI FY. This flag , w hen set t o t r ue, w ill send an Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce email t o t h e pr ofessor t hat t he salar y has chan ged. Th e follow ing show s t he ch anged cod e. A for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly par am et er has been added t hat has a defau lt . int ellig en t , com plex dat abases. [ Team LiB ]

CREATE OR REPLACE PROCEDURE update_professor

(v_prof_name [ Team LiB ] v_salary v_tenure v_notify

professors.prof_name%TYPE, professors.salary%TYPE := NULL, professors.tenure%TYPE := NULL, BOOLEAN := FALSE);

Wit h t his chan ge, old cod e is not aff ect ed. New cod e can p ass a TRUE/ FALSE v alue or n ot pass an yt h ing, u sin g t he def ault . For t his scenar io, t her e ar e t w o op t ions t o con sid er . 1 . The old code p lay s n o par t in t he new f un ct ion alit y . Per for m t h e follow ing st ep s if only new coded w ill use t his f eat ur e. Set t h e defau lt f or V_NOTI FY t o FALSE. •

Mod if y ofUPDATE_PROFESSORS t o send an em ail w h en t h e V_NOTI FY is TRUE. Table Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

En su re t hat all new code specifies a TRUE/ FALSE ( or default ) v alue depend in g on w het her an em ail sh ould be sent .

By Kevin Owens

Ther e is no imp act t o ex ist ing cod e. Pub lish er: Prent ice Hall PTR Dat old e: Decem ber or 0 5,som 2 003e of it , w ill use t h e new f unct ionalit y . To mak e t h is adj ust m en t , do 2 .Pub The code, t he follow g. 33 -0 I SBN: 0- 13in -0 850 Pages: 44 8

Set t h e defau lt f or V_NOTI FY, t he most com m on sit u at ion. For ex amp le, assum e m ost old cod e w ill sen d an em ail. I n t h is case, set def ault t o TRUE. Ef fect ively Mod creatif ey an d man age com plex dat w item h Or and FY datisabTRUE. ase ex per t UPDATE_PROFESSORS t oabases send an ail acle! w h enSy t hsteems V_NOTI Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you ou nall eed t o code kn ow specifies t o build rob ust an d com plex) / FALSE dat ab ases f oriny our b usiness. Enwsuhat re tyhat new a TRUE ( or d ef ault v alue t he call to UPDATE_PROFESSORS. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e Mod of Or es such as twrig and stan ored pr oced es- af eat u r es t hat ar allow our if yacle t hefeat old ur code, w hich ill gers not send email and ur add n ew FALSE gu myen t dat ab ases in t o tincor port at bu ATE_PROFESSOR. siness r ules w hich Most ar e easy t o man age m odifbyecause as t he it w ill he call o e UPD old cod e w ill notand ch ange bu sin ess evolv ed include: use es. t h e Topics defau ltcov of er TRUE. View in g const r aint s in t h e dat a dict ion ar y

10.8.8 %TYPE

Com plex r ule enf orcem en t This % TYPE sy nt ax is a m ean s t o d eclar e a v ar iable w hose t y pe is d er iv ed f rom a par t icular p r ogr am it st able. and langu age f eatf or u res columPL/ n t SQL yp e in a dat abun ase The sy nt ax t his t yp e definit ion is: Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions variable_name table_name.column_name%TYPE; Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ocedu r es t hat r et ur n dat a t o a calling p rog ram m ust be con cer ned w it h t h e size or dim ension of tOracle h e v ariable t o swand hichStt hey w rit in e itcalled ogrinv amaluable w r it es rdat a rce Pr ogr am m ing Tr igger or edarPreoced urg. es Wh , Then ir dt hEd ion , ispran esou tfor hatdat is abase lar ger dt han w hat t he caller is exp ect ing , t he r esult is an ov erf low condit ion . Declar ing ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly vint ariab les u sin g a % TYPE sy nt ax can m inim ize t his p rob lem . ellig en t , com plex dat abases. Con siderLiB t he [ Team ] pr oced ur e t hat r et ur ns an OUT m ode var iable, a pr ofessor s salary .

[CREATE Team LiB OR ]REPLACE PROCEDURE get_professor_salary (v_prof_name IN professors.prof_name%TYPE, v_salary OUT professors.salary%TYPE);

Now consider t h e PL/ SQL t h at u ses t h is pr ocedu r e. I t m ust d eclar e a salar y var iable. Wh at should t hat t y pe b e? The f ollow in g is n ot a good choice:

DECLARE SAL NUMBER(5,2); BEGIN get_professor_salary('Milton', SAL); • Table of Content s END; Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d

Edi ti on

By Kevin Owens

This code block will f ail if t he dimension of t he salar y colu m n in t he pr ofessor s t ab le incrPub eases. Supp ose t he salary recor ded in t he t able chang es fr om a mon t hly t o an annual lish er: Prent ice Hall PTR salary . Th e colu mn d im ension in t h e dat ab ase w ou ld incr ease. Execut ion of t he b lock w ou ld Pub Dat e: Decem ber 0 5, 2 003 fail w it h a VALUE_ERROR ex cept ion . This w ould occu r as t h e GET_ PROFESSOR_SALARY I SBN: 0- 13 -0 850 33 -0 at t em pt s t o w r it e a n um ber larg er t han NUMBER( 5 ,2 ) . Pages: 44 8

The p r eceding block should be w r it t en as:

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. DECLARE professors.salary%type UsingSAL easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake BEGIN adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SAL); dat abget_professor_salary('Milton', ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he END; bu sin ess evolv es. Topics cov er ed include: in g const r aint s in e datfuanct dict ionsp arecificat y UsingView % TYPE w it h pr oced ur et hand ion ions p rov ides add it ional inf or mat ion t o t he user . I t con vey s specif ic infor m at ion about t he dat a ex pect ed . A p r ocedu re t hat updat es a Com plexd rcould ule enf st udent r ecor b orcem e definen edt w it h t he f ollow in g: PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions PROCEDURE update_student(student IN VARCHAR2, etc); I nt er - pr ocess com mu nicat ions The u ser of t his pr oced ur e has t o dig int o t he code t o see w het her t he par amet er is a st udent Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch nam e of a st udent I D. Som eone fam iliar w it h t he d at abase sch em a mig ht under st and t hat t he m or e par am et er mu st be a pr im ary key and , t h er efor e, t his p rocedur e r equir es a STUDENT_ I D. The m ym ofing t heOracle in t er f ace is easily w it hur%esTYPE. Pr yst ogrer am Tr igger s andelim St orinat ed ed Pr oced , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] PROCEDURE update_student (student IN students.student_ID%TYPE, etc);

[You Team LiB ]not use a % TYPE w hen per for m ing an aggr egat ion. I f t h e r esult of a sub pr ogr am should call is t he su m of all salaries, t he com pu t ed nu m ber could ex ceed t he p recision of t he % TYPE. The f ollow in g r et ur ns a NUMBER w it h no p recision or scale.

CREATE OR REPLACE PROCEDURE get_professor_salaries (salaries OUT NUMBER) IS BEGIN SELECT SUM(salary) INTO salaries FROM professors; END get_professor_salaries;

• o Oracle except Tw Table ofions Content cans occur w hen a d at at y pe does n ot m at ch t he assig ned dat a. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

This ex cept ion is r aised in PL/ SQL w hen t he size of t h e t ar get is sm aller t han n eeded. You g et t his w h en y ou assign 10 0 t o a v ar iable declared w itPTR h NUMBER( 2) . This is r aised w hen you assig n a 3- char act er st rin g, Prent ice Hall such as " 100 , " t o a f ield declar ed as NUMBER( 2 ) . I f you SELECT I NTO a Decem ber 0 5, 2 003 v ariab le wit h t oo small a pr ecision, y ou get t his err or .

VALUE_ERROR Pub lish er: Pub Dat e:

I SBN: 0- 13 -0 850 33 -0

INVALID_NUMBER Pages: 44 8 This ex cept ion can occur w hen a SQL st at ement select s char act er d at a int o a NUMBER t y pe. This im plicit conv ersion w ill fail if t h e ch aract er st r in g does not repr esen t a valid num b er . fect ively e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t [EfTeam LiBcreat ] Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

10.9 Overloading You can ov erload t h e pr ocedu r e or fu nct ion in a packag e. The best ex am ple of ov er loading is t he Or acle b uilt - in D BMS_OUTPUT pack age. I t p r ovides a pr int pr ocedu re t o d isplay a st rin g:

PUT_LINE(parameter VARCHAR2) •

Table of Content s

Otogr Pr h eramt yp m ing es Or can a cl e be ® Tr pri gger int ed s and in clud Storing e d Paroce DATE durean s, Thir d NUMBER d Edi ti on t y pe. Th is leads t o ov erloaded pr oced ur es: By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0VARCHAR2) PUT_LINE(parameter Pages: 44 8 PUT_LINE(parameter DATE) PUT_LINE(parameter NUMBER)

You over load pr ocedu h en com ident ical dat f unct ionalitwyitis p eracle! f ormSy edston d iffer can Ef fect ively creat e an d res manwage plex abases h Or ems andent datt yp abes. aseYou ex per t tKevin echnically over p rocedur t hacle's at peransw for m er u nr nctur ions. This pLangu ract iceage m ak es code Ow ens exload plor es PL/ SQL,esOr t oelat t h eedStfu r uct ed Query ( SQL) , an d t hat usesyou y our p ack agen eed v agut oe, kn har ead, rob an dust h ard undplex er st and . ases f or y our b usiness. eaches w hat y ou owd t o rbuild an dt ocom dat ab Sub pr ogr amt so-wfollow it hin ainst pack age beexov erload only w h en t he par amet erues p rof is Using easyr uct ionscan an d am ples,ed t his book pr esent s t echniq t oile t ake dif enag t . eOrofacle mu stfeat beurable t o det w hich oced ur youurcall. p ack age advfer ant Or acle es such asertm rigine gers and pr st ored preoced es- f The eat u frollowin es t hat gallow y our cont ains over rocedur es. This ex amp le ar is enot valid because t he bmase e of dat ab ases t o load incored porpat e bu siness r ules w hich easy t o man age and odiftyypas t heeach par amess et erevolv is t he e. cov er ed include: bu sin es.sam Topics View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t CREATE OR REPLACE PACKAGE sample_pkg IS PL/ SQL p r ogr am un it s and langu f eat u res PROCEDURE process(v_value INage NUMBER); PROCEDURE process(v_value IN INTEGER); Dat a t y pes and comp osit e st r u ct u re END sample_pkg; Er r or han dling and except ions You can successfu lly com pile t h is packag e bu t Or acle w ill not kn ow w hich pr ocedu re t o inv ok e I nt er - pr ocess com mu nicat ions if you m ak e t he follow in g call. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly sample_pkg.process(2); int ellig en t , com plex dat abases. [ Team LiB ] This st at em en t w ill f ail w it h t he Or acle m essage:

[ Team LiB ] PLS-00307: too many declarations of 'PROCESS' match this call.

A m od if icat ion t o t he SAMPLE_ PKG p ack age cor r ect s t h is pr oblem . The f ollow in g code defines t w o p r ocedu res, each w it h a u nique pr ofile. This is a valid exam ple of ov erload in g.

CREATE OR REPLACE PACKAGE sample_pkg IS PROCEDURE process(v_value NUMBER); PROCEDURE process(v_value INTEGER, v_date DATE); END sample_pkg; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Dif ferences in MODE d o not const it ut e d iffer ences in pr of ile. Th e follow ing is inv alid . By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 13 -0 850 33 -0 CREATEI SBN: OR 0REPLACE PACKAGE sample_pkg IS Pages: 44 8 PROCEDURE process(v_value IN NUMBER); PROCEDURE process(v_value OUT NUMBER); END sample_pkg;

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Dif ferences forplor m alespar et erOrnam es answ do n ot ocedu es u niqu e. Thage e follow ing w dill Kevin Ow ensinex PL/am SQL, acle's er mt oakt he et he St rpr uct ur ed rQuery Langu ( SQL) , an com pile you but twhe ust u am ed not at ion Logan ically , t his w it hf or the concep t of t eaches hatcaller y ou m n eed t oseknnow t o build rob.ust d com plexconf datlict absases y our b usiness. ov er loading , w hich is t o b e able t o perf or m sim ilar op er at ions of d iff er ent dat at y pes. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: CREATE OR REPLACE PACKAGE sample_pkg IS PROCEDURE process(v_new_salary IN View in g const r aint s in t h e dat a dict ion ar yNUMBER); PROCEDURE process(v_old_salary IN NUMBER); Com plex r ule enf orcem en t END sample_pkg; PL/ SQL p r ogr am un it s and langu age f eat u res For t his p ack age, t he fir st call w or k s, but t he second does not . Or acle w ill r aise a r un - t ime a t y pes and comp st r w u ct u re pr oced ur e y ou wan t t o call. err or Dat b ecause it cannot detosit ermeine h ich Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch sample_pkg.process(v_new_salary=>9000); m or e sample_pkg.process(9000); Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Ov erload in g w or k s w hen t he p aram et er pr ofiles ar e dif ferent , w hich in clud es t he ev alu at ion of int ellig en t , com plex dat abases. t he base t y pes in conj un ct ion w it h defau lt par am et er s d eclar ed in t he specificat ion. [ Team LiB ] The f ollow in g is a case wh er e ad ding a d ef ault t o an ov er loaded pr oced ur e br eaks t he code. Mod if y SAMPLE_PKG and add a DATE par amet er w it h a d ef ault , show ing t h is ch ange as:

[ Team LiB ] CREATE OR REPLACE PACKAGE sample_pkg IS PROCEDURE process(v_value NUMBER); PROCEDURE process(v_value INTEGER, v_date DATE := SYSDATE); END sample_pkg;

The p ackag e is now a pr oblem . A call t o t he p rocedu re p r ocess using t he d ef ault dat e w ill f ail. The f ollow in g p r ocedu re call cann ot b e r esolv ed . Or acle can not d et er m ine if t he user in t en ds t o call t he f ir st p r ocedu re or t he secon d pr ocedu re using t he d ef ault .



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

sample_pkg.process(2); By Kevin Owens

This call p rod uces t he sam e err or —t oo man y declar at ions. Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

PLS-00307: too many declarations of 'PROCESS' match this call. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Cod e rOw ev iew evplor en es inf PL/ or mal revOr iew s, aransw e opperortt ounit on tLangu he r easonableness Kevin enss,ex SQL, acle's t h ies e Stfor r uctfeed ur edback Query age ( SQL) , anof d ov er loading w it hin a packag e. The DBMS_ OUTPUT packag e is alw ays an ex cellen t ex bamp le t o t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our usiness. pon der w hen design ing over loaded p r ocedu res. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our [ Team LiB ] dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Chapter Eleven. PL/SQL Language Features 11 .1 COMMENTS 11 .2 ASSI GNMENTS AND STATEMENTS 11 .3 BOOLEAN EXPRESSI ON •

11 .4 EXPRESSI ONS WI Table of Content s TH NULL

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

11 .5 LOGI CAL OPERATORS

By Kevin Owens

11 .6 STRI NG CONCATENATI ON Pub lish Prent ice Hall C PTR 11 .7er: ARI THMETI EXPRESSI ONS Pub Dat e: Decem ber 0 5, 2 003

11I SBN: .8 VARI DECLARATI ONS 0- 13ABLE -0 850 33 -0 Pages: 44 8

11 .9 TYPES 11 .9 . 1 Boolean Ef fect ively 11 creat .9 . 2 e Scalar an d man Typage es com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 11w.9hat . 3 Record s t eaches you y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. .9follow . 4 % ROWTYPE Using easy-11 t oinst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our . 5 I ndex BybuTables dat ab ases 11 t o .9 incor por at- e siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: 11 .9 . 6 Var ray s an d Nest ed Tab les 11g .9 . 7 Obr aint ject ss in t h e dat a dict ion ar y View in const 11 .9r.ule 8 Larenf georcem Obj ect Com plex ens t( LOBs) 11 0 I FpSTATEMENT PL/.1 SQL r ogr am un it s and langu age f eat u res .1 0.and 1 Simcomp ple I osit F e st r u ct u re Dat a 11 t y pes .1dling 0. 2 I f-and Th enexcept - Else ions Er r or 11 han 0. 3 I fTh en it h Else I nt er -11 pr .1 ocess com mu- Elsif nicatw ions I f- Thr en - Elsif No Else p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Declar11 at.1 iv0. e 4const aint s, including m or e 11 .1 0. 5 St at em en t Exp ression s Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce 11 d .1ev 0.elopers, 6 Use D ECODE for dat abase d esign and er s, CASE and prin oj SQL ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. 11 .1 1 CASE STATEMENT [ Team LiB ] 11 .1 1. 1 Searched CASE St at em en t 11 .1 1. 2 CASE w it h Select or

[ Team LiB11 ] .1 1. 3 Using CASE w it hin t h e SELECT 11 .1 1. 4 Using D ECOD E w it h in t h e SELECT 11 .1 2 LOOP 11 .1 2. 1 DO UNTI L LOOP 11 .1 2. 2 WHI LE- LOOP 11 .1 2. 3 FOR LOOP 11 .1 2. 4 DO- WHI LE- DO LOOP 11 .1 2. 5 En cap su lat ing t he Logic of t he Loop •

11 .1 3 STRI NG MANI PULATI ON FUNCTI ONS Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

11 .1 3. 1 SUBSTR

By Kevin Owens

11 .1 3. 2 I NSTR .1 3. LPAD , RPAD Pub lish er:11 Prent ice3 Hall PTR Pub Dat e: Decem ber 0 5, 2 003

11 .1 3. 4 LTRI M, RTRI M

I SBN: 0- 13 -0 850 33 -0

Pages:11 44.1 8 3. 5 REPLACE

11 .1 3. 6 TRANSLATE .1 4creat MI SCELLANEOUS STRI FUNCTI ONS w it h Or acle! Sy st ems and dat ab ase ex per t Ef fect11 ively e an d man age comNG plex dat abases Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 11 .1 5 NUMERI t eaches you w hat y C ouFUNCTI n eed t oONS kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. .1 6 RANDOM GENERATI ONples, t his book pr esent s t echniq ues t o t ake Using11 easyt o- follow NUMBER inst r uct ions an d ex am adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 11 .1 7 DATE FUNCTI ONS dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: 11 .1 7. 1 SYSDATE 11 .1 7. 2 TO_ CHAR, TO_DATE View in g const r aint s in t h e dat a dict ion ar y 11 .1 7. 3 ADD_ MONTHS Com plex r ule enf orcem en t 11 .1 7. 4 LAST_ DAY PL/ SQL p r ogr am un it s and langu age f eat u res 11 .1 7. 5 MONTHS_ BETWEEN Dat a t y pes and comp osit e st r u ct u re 11 .1 7. 6 NEW_ TI ME Er r or han dling and except ions 11 .1 7. 7 NEXT_ DAY I nt er - pr ocess com mu nicat ions 11 .1 7. 8 ROUND, TRUNC Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e 11 .1 8 EXCEPTI ONS Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce 11 .1 8. 1 User - Defined Ex cep t ions for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , 11 com plex dat abases. .1 8. 2 Blocks w it h Ex cep t ion Han dlers [ Team LiB11 ] .1 8. 3 The EXCEPTI ON Clause 11 .1 8. 4 SQLCODE and SQLERRM

[ Team LiB11 ] .1 8. 5 The RAI SE St at em ent 11 .1 8. 6 Unhan dled Except ions an d Ex cept ion Pr opagat ion 11 .1 8. 7 RAI SE_ APPLI CATI ON_ERROR 11 .1 8. 8 EXCEPTI ON_I NI T 11 .1 9 DATABASE ACCESS WI TH SQL 11 .1 9. 1 CURSOR FOR LOOPS 11 .1 9. 2 Select w h en Ex pect ing a Sin gle Row 11 .1 9. 3 I nser t s and Up dat es •

11 .1 9. 4 Ex plicit Cu r sor s Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

11 .2 0 SENDI NG PI PE MESSAGES ( DBMS_ PI PE)

By Kevin Owens

11 .2 0. 1 Send- Receive Exam p le .2 0. I nt er face Pub lish er:11 Prent ice2 Hall PTR

Descr ipt ion

Pub Dat e: Decem ber 0 5, 2 003

11 .2 0. 3 Ex cep t ion Han dling

I SBN: 0- 13 -0 850 33 -0

Pages: 44GNALI 8 11 .2 1 SI NG EVENTS WI TH ALERTS ( D BMS_ALERT)

11 .2 1. 1 I nt er face Descr ipt ion .2 2creat EMAIeL an NOTI FI CATI WI TH TRI GGERS wAND ALERTS Ef fect11 ively d man ageON com plex dat abases it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d [t eaches Team LiB you] w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.1 Comments The d ouble h yp hen ( - - ) is u sed t o com m ent a sin gle line. A slash follow ed by an ast er isk ( / * ) begins a block com m en t . An ast er isk follow ed b y a slash ( * / ) end s a b lock com m en t . The C- st yle com m en t s ( / * , * / ) can b e used t o block out a sect ion of code. The follow in g pr oced ur e illust rat es b ot h for m s.



Table of Content s

--ogrFilename Pr am m ing Or ahello.sql cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on CREATE OR REPLACE PROCEDURE hello IS By Kevin Owens str CONSTANT VARCHAR2(15) := 'Hello World!'; len INTEGER; /* length of the constant */ BEGIN Pub lish er: Prent ice Hall PTR -Pub Dat e: Decem ber 0 5, 2 003 -- Set len to length of character string. I SBN: 0- 13 -0 850 33 -0 -Pages: 8 len :=44LENGTH(str); /* * write the string length Ef fect*/ ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevindbms_output.put_line(str||'-string Ow ens ex plor es PL/ SQL, Or acle's answ er length:'||len); t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. END hello; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv antcom ag emof Ors acle es such st asatt em rig gers and befor st ored oced f eat u rifesyou t hatarallow y our Place ent af t erfeat t heurCREATE en t , not e. pr This onur lyesapplies e using a ases e bu siness r ules t w hich ar easeasy man age odif tdat extabedit or two itincor h a tpor ool at like SQL* Plus—a ool such JDevt oeloper w illand n ot m per m ity yas out he t o p lace bu sinment ess evolv es.t oTopics cov ersted include: com s pr ior a CREATE at em ent . Th e sit uat ion t o av oid is t he f ollow ing : View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t -- This procedure prints hello. PL/ SQL p r ogr am un it s and langu age f eat u res CREATE OR REPLACE PROCEDURE hello IS str CONSTANT VARCHAR2(10) := 'Hello World!'; Dat a t y pes and comp osit e st r u ct u re . . . etc Er r or han dling and except ions Com mI nt ent t h ocess at p reced t henicat CREATE ers- pr comemu ions st at em en t ar e not included w it h t he sour ce cod e saved in t he d at a dict ionar y . Com m ent s af t er t he CREATE clause ar e st ored in t he dat a dict ionar y . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Packag m es or erequ ire ex t ensiv e com m en t s, m ost ly b ecause t h ey t yp ically hav e m any pr ocedu res and f unct ions t hat p r ovide a w ealt h of f unct ionalit y . A packag e should hav e ov er v iew com t hatOracle descr ibe t h e spack ervur iew Oraluable acle pr ivileges Pr ogrment am ms ing Tr igger andage. St or This ed Prov oced es should , Th ir d docum Ed it ionent , is any an inv r esou rce r eq uir t o use packag e. I t should ent tshelook n eed ase par amt ret er for dated abase d evt he elopers, d esign er s, andalso pr ojdocum ect leader in g for t o bany uilddat anab dm aint ain uly setellig t in gs. int en t , com plex dat abases. Som et imLiB es ]t h er e is an or dered depend en cy am on g t he subp rog r ams in t h e packag e. For [ Team exam ple, t o use a packag e pr oper ly , y ou m ay hav e t o call on e subp rog ram fir st , pr ior t o callin g ot h er pr oced ur es. You w ant t o d ocum en t t h is dependency . An over v iew t hat in clu des ex am ples t hat dem onst r at e how t o u se t he pack age is v ery usef ul.

These er v]iew com m ent s im m ed iat ely f ollow t he CREATE PACKAGE st at em en t . Follow ing t h e [ TeamovLiB gener al com ment s are t he p rocedur e an d f un ct ion defin it ion s, w hich h ave in divid ual com ment s.

PACKAGE students_pkg is ---general comments about how to use the package ---- comments on print_name PROCEDURE print_name (v_student_id IN VARCHAR2); -• Table of Content s -- comments on print_major Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on PROCEDURE print_major (v_student_id IN VARCHAR2); By Kevin Owens END students_pkg;

lish er: b Prent PTRages ar e w ell docum ent ed w it h an ov er v iew sect ion, f r eq uent ly ThePub Oracle uiltice - inHall p ack Pub Dat e: Decem ber 0 5, includin g ex amp les, p lu2 s003 det ailed com m en t s on each pr oced ur e and f unct ion. I SBN: 0- 13 -0 850 33 -0

PackagPages: es you 44 8can use ar e available t hr ough t he ALL_ SOURCE view . This view cont ains t he sour ce you hav e w r it t en, as well as code in ot h er schem as t o w hich y ou hav e access. This includes t h e Or acle built - in packag es. Th e int er face and com ment s t hat descr ibe t h e DBMS_ OUTPUT packag e can b e ex t r act ed f r om t he ALL_SOURCE view w it h a SQL st at em en t similar t o t hat used t o ext ract t he HELLO sour ce and com m ent s. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SQL> SELECT text FROM all_source dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he 2 WHERE name='DBMS_OUTPUT' bu sin ess evolv es. Topics cov er ed include: 3 AND type='PACKAGE'; View in g const r aint s in t h e dat a dict ion ar y [ Team LiB ] Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.2 Assignments and Statements The assignm ent oper at or is:

":="

• The assignmTable ent oper of Content at or is s not " = " , b ut t he if- t est ex pr ession is. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

IF (a = b)

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

44 8 We d oPages: not code:

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d IF (a == t eaches youb)w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake You canagassign er alfeat v alues, or exp s t hat s and ar iables. adv ant e of Orlit acle ur es such asression t rig gers andinclude st ored operat pr ocedion ur esf eatot u rher es tvhat allow yYou our can wrases ap exp preovbu idsiness ed t h er st at ement not br t heand m iddle ofyaas v ariab dat ab t o ression incor pors at ules w hich does ar e easy t oeak maninage m odif t he le nam bu sine.ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t base_monthly_salary := 10000; PL/ SQL p r ogr am un it:= s and langu age f eat u res base_salary_increase 1000; new_professor_salary := base_monthly_salary * 1.1; Dat a t y pes and comp:= ositbase_monthly_salary e st r u ct u re new_profrssor_salary + base_salary_increase; Er r or han dling and except ions I nt er - pr ocess mu nicat You can d eclar e a v com ar iable w it h ions an init ialized v alue. You can in it ialize it w it h NULL. Do not assu m e any init ial v alue of a v ariab le t hat is declar ed w it h no init ial set t ing. You can declar e Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch an init ialized v ariab le and con st rain it t o NOT NULL. The follow ing PL/ SQL declares sever al m or e v ariab les. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] DECLARE total_credits total_credits_2 credit_hour

NUMBER(3,1); NUMBER(3,1) := NULL; NUMBER(2,1) := 3.0;

no_credit CONSTANT NUMBER(2,1) := 0; [ Team LiB ] pass_fail_credit NUMBER(2,1) NOT NULL := 0; BEGIN PL/SQL code here. END;



TOTAL_CREDITS

This is a basic declarat ion of a NUMBER f or t hr ee digit s: t w o t o t he left of t he decim al p oin t , one place t o t h e r ig ht .

TOTAL_CREDITS_2

Sam e as TOTAL_CREDI TS ex cept t he var iable is init ialized t o NULL.

CREDIT_HOUR

This v ar iable has a defau lt assig nm ent . Th e valu e can chan ge any t im e w it hin t he code block .

NO_CREDIT

This is a const ant . Const ant s are a for m of self- d ocu ment in g cod e. When y ou u se a const ant , you ar e docum ent in g t h e fact t hat t his Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on v ariab le is t o h ave n o ot h er value.

Table of Content s

Pr ogr am m ing Or a cl e ® By Kevin Owens

PASS_FAIL_CREDIT I f you d eclar e a v ar iab le as NOT NULL, t h en y ou mu st assig n a defau lt v alue in t he sam e declar at ion . Pub lish er: Prent ice Hall PTR

You Pub canDat code e: Decem a NULL ber 0 5,st2at 003 em ent . For ex am ple, t he f ollowin g is a v alid PL/ SQL block and w hen execut ed, I SBN:d eclar 0- 13 -0es 850var 33 -0iables and exit s. Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t DECLARE Kevintotal_credits Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d NUMBER(3,1); t eaches you w hat y ou n eed t o kn ow t o build ust an d com plex dat ab ases f or y our b usiness. total_credits_2 NUMBER(3,1) := rob NULL; credit_hour NUMBER(2,1) := 3.0; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake no_credit CONSTANT NUMBER(2,1) := 0; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our pass_fail_credit NUMBER(2,1) NOT NULL := 0; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he BEGIN bu sin ess evolv es. Topics cov er ed include: NULL; END; View in g const r aint s in t h e dat a dict ion ar y A comCom m onplex user of attement is w it hin an ex cep t ion hand ler w her e y ou wan t t o cat ch ulet he enfNULL orcemsten t he ex cep t ion b ut int end no act ion . For ex am ple: PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions EXCEPTION I nt er -DUP_VAL_ON_INDEX pr ocess com mu nicatTHEN ions NULL; WHEN END; Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e [ Team LiB ] Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.3 Boolean Expression Boolean ex pr essions u se t he oper at or s: AND OR NOT A Boolean exTable pr ession can ev aluat e t o TRUE, FALSE, or possibly not evaluat e t o an yt h ing. An • of Content s exp ression d oes n ot ev aluat e w hen it cont ain s a NULL—t his t op ic is cov ered in t he nex t Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on sect ion, " Ex pr essions wit h NULL. " By Kevin Owens

Leng t hy Boolean ex pr essions can be d iff icult and t im e consum ing t o in t er pr et . You can lessen t he im p act of har d- t o- read logic if you w r ap long Boolean exp ression s int o a PL/ SQL fun ct ion ice Hall PTR t hatPub r etlish urer: nsPrent a BOOLEAN. Pub Dat e: Decem ber 0 5, 2 003

For exam ple, w -0 it hin t he I SBN: 0- 13 850 33 -0 body of a PL/ SQL p rocedur e, it cou ld t ak e som e t im e t o d igest t he follow ing logic. Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow((status ens ex plor=es'PART PL/ SQL, Or acle's answ er t=o t'FULL h e St r uct ur ed Query Langu age ( SQL) , an d If NOT TIME' OR status TIME') t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. AND (balance = 0) AND NOT (college_major = 'Undeclared')) THEN Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ases t o incor por at e bu e easy m odif y as Theab sam e logic, w hen emb edsiness ded inr ules a funwcthich ion , ar simp lif iest ot oman t h eage cod and e. The f ollow ingt he p rocedur e bu sin ess evolv es. Topics cov er ed include: encapsulat es t he Boolean logic int o a f unct ion by t h e nam e: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t registered_student_with_no_credit(). PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re This is a long fu nct ion n am e, but w hen u sed in t he b ody of t he PL/ SQL pr ogr am , conv eys t he Boolean t est b ein g p and er f orm ed. ions Er r or han dling except I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e PROCEDURE process_student_registration (. . .) Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce IS for dat d evfunction elopers, d that esign er s, and pr oj ect this leaderlogic. s look in g t o b uild an d m aint ain t r uly --abase Local encapsulates int ellig en t , com plex dat abases. FUNCTION registered_student_with_no_credit RETURN BOOLEAN IS [ Team LiB ] BEGIN RETURN NOT ((status = 'PART TIME' OR status = 'FULL TIME') AND (balance = 0)

[ Team LiB ]AND NOT (college_major = 'Undeclared')); END registered_student_with_no_credit; BEGIN . . . body of procedure . . . IF registered_student_with_no_credit THEN Do something . . . ELSE Do other thing END IF; END process_student_registration;

A p r ogr amm er can look at t h e body of t his pr ocedur e and g et an id ea of w hat t he code does. A g en er al under st andin g is t hat t he code look s at st u dent s w it h out cr edit . Logic is execut ed • Table of Content s based on t h at t est . Th e com p lex Boolean log ic is st ill in t h e pr oced ur e, localized t o a fun ct ion . Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on The p r ogr amm er can dig in t o t hat log ic if n ecessar y . The encap su lat ion of t h e Boolean code By Kevin Owens allow ed t he pr ocedu r e t o b e r ev iew ed in st eps. Pub lish er: ]Prent ice [ Team LiB

Hall PTR

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.4 Expressions with NULL The com binat ion of a NULL w it h an AND in a pr ed icat e w ill n ot g iv e y ou t he r esult s y ou exp ect . A v ariab le t hat is NULL h as no value. Th er efor e, y ou can not com par e it t o an yt h ing else w it h m eaningf ul r esult s. An ex pr ession of comp arison w it h a NULL does not ev aluat e. When such an ex pr ession ex ist s w it hin an I F st at em en t an d t here is an ELSE par t , t h e code does n ot evalu at e t o TRUE, so it follow s t he ELSE pat h . From t his, it can app ear t hat t he condit ion evaluat es t o FALSE. I f y ou t hen r ev erse t h e logic in t he I F t est w it h a NOT oper at or , t he sam e ELSE pat h is t ak en . Con sider t wo v ariables: OTHER_NAME an d MY_NAME. A NULL init ializes t h e v ariable •OTHER_NAME. Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

my_name VARCHAR2(100) := 'SCOTT'; Pub Dat e: Decem ber 0 5, 2 003 other_name VARCHAR2(10) := NULL; I SBN: 0- 13 -0 850 33 -0

Pages: 44 8

The f ollow in g ex pr ession does not ev aluat e:

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. IF (my_name = 'SCOTT' AND other_name = 'JOHN') THEN Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Becau se t his ression oes n ot ev aluatwe,hich it cann p ossibly alu and at e tm o odif TRUE. dat ab ases t o exp incor por at edbu siness r ules ar e ot easy t o manev age y asHence, t he t he follow ing evolv PL/ SQL ill f ollow heedELSE pat h . bu sin ess es. wTopics covter include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t set serveroutput on PL/ SQL p r ogr am un it s and langu age f eat u res DECLARE my_name VARCHAR2(10) := 'SCOTT'; Dat a t y pes andVARCHAR2(10) comp osit e st r u:= ct u reNULL; other_name BEGIN Er r or han dling and except ions IF (my_name = 'SCOTT' AND other_name = 'JOHN') THEN dbms_output.put_line('CONDITION_TRUE'); I nt er - pr ocess com mu nicat ions ELSE dbms_output.put_line('CONDITION_FALSE'); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch END IF; m or e END; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Theellig r esult t h is scr dat ipt abases. is t he f ollowin g ( not ice t he ex ecut ion pat h f ollows t he ELSE par t ) . int en t , of com plex [ Team LiB ]

CONDITION_FALSE

PL/SQL procedure successfully completed. [ Team LiB ] SQL>

Based on t his ou t come, t h e opp osit e of t he I F condit ion should t ak e t he op posit e execut ion pat h . That is, if we put a NOT befor e ou r t est , t hen t he code sh ould NOT t ak e t h e ELSE p at h and display CONDI TI ON_TRUE. Th e follow ing PL/ SQL b lock is ch anged. Th e only chan ge is t o place a NOT in t he I F st at em en t .

set serveroutput on DECLARE my_name VARCHAR2(10) := 'SCOTT'; • Table of VARCHAR2(10) Content s other_name := NULL; Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on BEGIN IFOwens NOT (my_name = 'SCOTT' AND other_name = 'JOHN') THEN By Kevin dbms_output.put_line('CONDITION_TRUE'); ELSE Pub lish er: dbms_output.put_line('CONDITION_FALSE'); Prent ice Hall PTR END IF; Pub Dat e: Decem ber 0 5, 2 003 END; I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

The r esult of t h is scr ipt is t he sam e. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. CONDITION_FALSE Using easyt o- follow successfully inst r uct ions an dcompleted. ex am ples, t his book pr esent s t echniq ues t o t ake PL/SQL procedure adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our SQL> dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: Based on t he pr eceding t w o PL/ SQL block s, t he f ollow ing is nev er t r ue View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res (my_name = 'SCOTT' AND other_name = 'JOHN') Dat a t y pes and comp osit e st r u ct u re The f ollow g isdling also and never t r ue:ions Er r or inhan except I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e NOT (my_name = 'SCOTT' AND other_name = 'JOHN') Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Theellig conen clusion om dat t h isabases. is t hat PL/ SQL cond it ion s w it h an AND par t and a NULL exp ression int t , com fr plex do not ev aluat e. Th ey d o n ot ev alu at e t o TRUE; t h ey do n ot ev aluat e t o FALSE. I f t her e is an ELSE p arLiB t in] t he I F st at em en t , t h e cod e w ill t ak e t hat pat h . [ Team A cond it ion w it h t he OR operat or t hat includes at least on e t est t h at evalu at es t o TRUE w ill behav e as ex pect ed . The f ollow in g ex pr ession disp lays CONDI TI ON_TRUE because, at least , t he fir st par t , MY_NAME= SCOTT is TRUE.

[ Team LiB ]

set serveroutput on DECLARE my_name VARCHAR2(10) := 'SCOTT'; other_name VARCHAR2(10) := NULL; BEGIN IF (my_name = 'SCOTT' OR other_name = 'JOHN') THEN dbms_output.put_line('CONDITION_TRUE'); ELSE dbms_output.put_line('CONDITION_FALSE'); END IF; END; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin This ouOwens t put is TRUE becau se at least MY_ NAME= SCOTT is t r ue.

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

CONDITION_TRUE Pages: 44 8 PL/SQL procedure successfully completed. SQL>

Ef fect ively creat e an an dOR man ageit ion comdplex abases it h ent Or acle! Syression st ems and abev ase ex per When all par t s of cond o notdat evaluat e, wt he ir e exp d oesdat n ot aluat e. t Kevin ens tex PL/ SQL, Or her acle's answ er FALSE. t o t h e St r uctI ur age (becau SQL) , se anitd I n t hisOw case, heplor st ates ement is neit TRUE nor The F ted estQuery fails t Langu o be TRUE tdoes eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. n ot evalu at e. This t ak es t he code t o t h e ELSE p art and leads one t o believ e t h at t h e condit ion does not evalu at e t o TRUE and m ust be FALSE. This is t h e case f or t h e follow ing: Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: set serveroutput on View in g const r aint s in t h e dat a dict ion ar y DECLARE my_name VARCHAR2(10) := 'SCOTT'; Com plex r ule enf orcem en t other_name VARCHAR2(10) := NULL; BEGINPL/ SQL p r ogr am un it s and langu age f eat u res IF (other_name = 'JOHN' OR other_name = 'SCOTT') THEN Dat adbms_output.put_line('CONDITION_TRUE'); t y pes and comp osit e st r u ct u re ELSE Er r ordbms_output.put_line('CONDITION_FALSE'); han dling and except ions END IF; END; I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch e p art of t he OR t est ev aluat es, t he en t ire t est does not ev aluat e. Th e r esult of t he Becaumseorno pr ecedin g b lock is t he f ollow ing out put . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] CONDITION_FALSE PL/SQL procedure successfully completed. SQL>

[ Team LiB ] Rev er sing t he log ic of t he I F t est does n ot r ever se t he ex ecut ion pat h, as show n nex t .

set serveroutput on DECLARE my_name VARCHAR2(10) := 'SCOTT'; other_name VARCHAR2(10) := NULL; BEGIN IF NOT (other_name = 'JOHN' OR other_name = 'SCOTT') THEN dbms_output.put_line('CONDITION_TRUE'); ELSE dbms_output.put_line('CONDITION_FALSE'); • Table of Content s END IF; Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on END; By Kevin Owens

The r esult is t he sam e. The I F condit ion does not evalu at e. I t follow s t h e ex ecut ion of t he Pubplish Prent ice Hall ELSE at er: h, sh own h erPTR e. Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

CONDITION_FALSE PL/SQL procedure successfully completed. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t SQL> Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. We can use t he NVL op er at or in t h ese sit uat ions. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our NVL is a f unct ion t hat t ak es t w o ar gum ent s. I f t h e fir st ar gum ent is NULL, t he NVL fu nct ion dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he r et ur ns t h e second ar gum ent . For t he f ollow ing , NVL ret u rn s 1 wh en ARG is NULL. bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t NVL(arg, 1) PL/ SQL p r ogr am un it s and langu age f eat u res You can NVLand f unct ions. Theisstallows Datnaest t y pes comp osit r u ct u reyou t o select a NOT NULL valu e fr om a list of candid at es. Consid er var iables: A, B, and C. You w ant A. I f it is NULL, t hen use B. I f t hat is NULL,Ert hen u sedling C. I f and all arexcept e NULL, r or han ionst hen u se zer o. Th e exp ression f or t his is: I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e NVL(A, NVL(B, NVL(C,0))) Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int t , com abases. Forellig t heen follow in plex g, w edat can r ep lace OTHER_NAME w it h a b lank only w h en it is NULL. This r em ov es NULLs f rom t he Boolean ex pr ession. [ Team LiB ]

set serveroutput on [ Team LiB ] DECLARE my_name VARCHAR2(10) := 'SCOTT'; other_name VARCHAR2(10) := NULL; BEGIN IF NOT (NVL(other_name,' ') = 'JOHN' OR NVL(other_name,' ') = 'SCOTT') THEN dbms_output.put_line('CONDITION_TRUE'); ELSE dbms_output.put_line('CONDITION_FALSE'); END IF; END; •

Table of Content s

The ou t pu t f rom t his block is: Pr ogr am m ing Or a cl e ® Tr i gger s and

Stor e d P roce dure s, Thir d Edi ti on

By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 CONDITION_TRUE PL/SQLI SBN: procedure 0- 13 -0 850 33 successfully -0 completed. SQL> Pages: 44 8

I n su mm ar y , use caut ion w hen wr it ing PL/ SQL pr ocedu r es t hat h ave I N or I N OUT m od e par am et er s an d t hose par am et er s ar e t o be em bedded in I F st at em en t s w it h ELSE logic. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Som eon e m ay call you r pr oced ur e passing a NULL and t h e cod e w ill ex ecut e a pat h t hat Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d m akes n o sense. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. A st r at egy is t o emp hasize NOT NULL const r aint s in t he schem a t ab les. By ap ply in g NOT NULL Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake const r ain t s, t he values r ead f r om select st at em en t s w ill not be NULL. A g oal should be t o adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our r ed uce t he num ber of NULL v ariab les w it hin an applicat ion. dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: You also hav e t he NVL f unct ion as show n earlier. You can use t h e NVL operat or in y our SQL select st at em en t s. This can be an init ial op por t unit y t o t r anslat e a NULL t o a b lank or zer o as y ou pView ull t hine gdat a fr rom abdat ase. const aintt sh eindat the a dict ion ar y You can r eplace datenf ab ase NULL Com plex r ule orcem en t def ault s w it h a NOT NULL value ( see Ch apt er 3) . A SQL I NSERT and UPD ATE p laces a NULL in t o a colu mn t h at is n ot r eferenced in t h e SQL st at ement . This is tam h e defau behav iorage . Con sider PL/ SQL p r ogr un it s ltand langu f eat u resa t able colum n t hat st ores a ch eck book balance. Mak e t h e defau lt a zer o r at h er t han NULL. PL/ SQL code t hat qu er ies check book d at a w ill get r atand her comp t han osit a NULL. decision t o u se a zero defau lt r at her t h an a NULL is Dataazero t y pes e st r uTh ct ue re because t he absen ce of m on ey , in t his case, is zer o. Th is elim inat es t h e con cer n w it h Erding r or han and balan exceptce ions emb ed a chdling eck book wit h in Boolean ex pr essions. I nt er - pr ocess com mu nicat ions [ Team LiB ] Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.5 Logical Operators PL/ SQL su ppor t s a fu ll set of log ical operat ors t hat may be used for logical an d ar it hm et ic exp ression s. The op er at ions d ef ined on D ATE t y pe allow man ipulat ion and com par ison of DATE t y pe v ar iables. Use " I S NULL" and " NOT NULL" in com par ison st at em en t s if any of t h e v alues m ay be NULL. The f ollow ing is a su m mar y of com par ison oper at or s.

•=

Table ofto Content s is equal IF (a = b) THEN Pr m ingnot Or a clequal e ® Tr i gger Thir d ti onTHEN !=ogr am is to s and Stor e d P roce dure IFs, (a !=Edib)

is not equal to IF (a

b) THEN By Kevin Owens > is greater than IF (a = b) THEN >= is greater than or equal to IF (a != b) THEN < Pub lish iser:less IF (a b) THEN Prent icethan Hall PTR VAR_2 THEN etc. •

Table of Content s The SQL fun ct ion s GREATEST, LEAST can assist . Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

SELECT COL_1, COL_2, Pub Dat e: Decem ber 0 5, 2 003 GREATEST(COL_1, COL_2) INTO VAR_1, VAR_2, VAR_3 etc. I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Refer t o Sect ion 11 . 14, " Miscellan eou s St r in g Fu nct ions," for a descript ion of GREATEST and LEAST—t hey also oper at e on st rin gs. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin ens [ TeamOw LiB ] ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.6 String Concatenation The con cat enat ion oper at or is:

||

•This op er at orTable conof catContent enat ess st r ings, b ut you can con cat en at e ot her t y pes. PL/ SQL d oes Pr am mconv ing Or cl e ® Tr i ggeras s and Stor P roce dure s, Thir d d Edidtiat one t y pe v ar iable t o a st r in g. Th is imogr plicit erasion, such conv eretding a num ber an enables st at ement s t o concat enat e var ious t y pes, bu t on ly if t he concat enat ed it em con ver t s By Kevin Owens t o a st r ing. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 DECLARE professor_name VARCHAR2(100) := 'Professor Smith'; hire_date DATE := SYSDATE; dalary NUMBER(7,2) := 10100.50; VARCHAR2(2000); Ef fectstr ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t BEGIN Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d stryou := wprofessor_name|| ' was hired on an '|| t eaches hat y ou n eed t o kn ow t o build rob ust d com plex dat ab ases f or y our b usiness. hire_date ||' with a salary of '|| Using easy- t ofollow inst rper uct ions an d ex salary||' month. ';am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dbms_output.put_line(str); dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he END; bu sin ess evolv es. Topics cov er ed include:

You pr ecede each sin gle quot e t hat is par t of t he st r ing w it h a quot e. For ex am ple, you r insgt o const r aint in t hlee quot dat a edict ion ar st r in gView need in clud e as sing b ecau sey t he fin al t ext m ust b e t his n ex t lin e: Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re A quote like ' is needed. Er r or han dling and except ions You prI nt odu his out p utmu bynicat pr eced in g t he qu ot e w it h a qu ot e. This ident if ies t he char act er as er ce - prtocess com ions a q uot e in t he st r ing r at her t h an t he end of t he st r ing . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly DECLARE int ellig en t , com plex dat abases. str varchar2(100); BEGIN [ Team LiB ] str := 'A quote like '' is needed.'; dbms_output.put_line(str); END;

[ Team LiB ] When qu ot es mu st begin or end a st r ing , y ou st ill hav e t w o quot es. You also hav e t h e st rin gt er min at in g quot e. You w ant t he out pu t t o be:

'A quote like ' is needed.'

You for m t h is st rin g w it h t he follow in g:



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on DECLARE str varchar2(100); By Kevin Owens BEGIN str := '''A quote like '' is needed.'''; dbms_output.put_line(str); Pub lish er: Prent ice Hall PTR END; Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 The SQL* Plu s en vir onm ent uses " &" for par amet er n ot at ion. Wh en y ou wr it e PL/ SQL in a SQL* Plus env ir onm en t , t he use of t his sy mb ol and t h e t ext t hat follow s it w ill be int er pr et ed as a SQL* Plu s par am et er . Th is is only an issue in SQL* Plus. To use & in a st r ing, replace it w it h t he CHR f unct ion. The CHR f unct ion is a bu ilt - in f unct ion t hat r et ur ns t h e ASCI I Ef fect ively e an d man age comIplex w it hI Or andRef dat exion per t Sect char act er frcreat om an equiv alen t ASCI n umdat berabases . The ASCI in tacle! eg er Sy forst&ems is 38. erabt oase Kevin ens ex plor PL/r in SQL, t o t h e St ed Query Langu 11 .1 4,Ow " Miscellan eoues s St g FuOr nctacle's ions,"answ for aerdescript ionr uct of ur CHR and ASCI I . I fage our( SQL) out pu, tan is:d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es.'Topics include: 'A quote like and acov & er isedneeded.' View in glay const dat aing dict You can d isp t hisr aint w it hs in t het hf e ollow . ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re DECLARE str varchar2(100); Er r or han dling and except ions ch varchar2(1) := CHR(38); BEGINI nt er - pr ocess com mu nicat ions str := '''A quote like '' and a '||ch||' is needed.'''; dbms_output.put_line(str); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch END; m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce [ Team LiB ] d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly for dat abase int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.7 Arithmetic Expressions All t h ir d- generat ion lang uage m at h em at ical oper at ions ar e p rov ided.

x := -1; -- x equals minus 3 y := -x; -- y equals 3 y := -((-3))*(-1)) -- y equals –3 •x := 2**10; Table of Content -- sx equals 1024 Pr ogr m ing Or a cl e ® Tr i gger Stor e d Pnumber roce dure s, d Edi ti on in a day x :=am1/((60/24) -- s xand equals ofThir seconds By Kevin Owens

[ Team LiB ] Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.8 Variable Declarations You declar e local sub pr ogr am v ariab les in t he declar at ive region bet w een t h e key w ord s: I S and BEGI N.

PROCEDURE procedure_name(. . .) IS • Table oftypes, Content svariables declare here. constants, Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on BEGIN body of code. By Kevin Owens END procedure_name; FUNCTION . .) RETURN some_datatype Pub lish er:function_name(. Prent ice Hall PTR IS Pub Dat e: Decem ber 0 5, 2 003 constants, types, variables declare here. I SBN: 0- 13 -0 850 33 -0 BEGINPages: 44 8 body of code. RETURN value_to_return; END function_name; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d The scope of a pr oced ur e or f unct ion var iable is on ly t he sub pr ogr am in w hich t h e v ariable is t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. declared. The f ollow ing is a packag e specif icat ion and bod y w it h t wo pr oced ur es. Each pr oced ur e has a single v ar iable. Each p r ocedu re is aut onom ous. Th e v ariab les NAME and Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake MAJOR ar e local t o t heir r espect ive su bpr ogr am s. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y PACKAGE students_pkg is PROCEDURE print_name IN VARCHAR2); Com plex r ule enf orcem en(v_student_id t PROCEDURE print_major (v_student_id IN VARCHAR2); END students_pkg; PL/ SQL p r ogr am un it s and langu age f eat u res PACKAGE Dat aBODY t y pesstudents_pkg and comp osit e IS st r u ct u re PROCEDURE print_status (v_student_id IN VARCHAR2) Er r or han dling and except ions IS name VARCHAR2(100); I nt er - pr ocess com mu nicat ions BEGIN SELECT student_name INTO name Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch FROM STUDENTS m or e WHERE student_id = v_student_id; dbms_output.put_line(name); Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce END print_status; for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly PROCEDURE print_major (v_student_id IN VARCHAR2) int ellig en t , com plex dat abases. IS major VARCHAR2(100); [ Team LiB ] BEGIN SELECT college_major INTO major FROM STUDENTS WHERE student_id = v_student_id;

dbms_output.put_line(major); [ Team LiB ] END print_major; END students_pkg;

You can d eclar e var iables in t he d eclar at ive p ar t of t h e packag e bod y. This m akes t h e v ariab les g lob al t o all pr oced ur es and fu nct ions w it hin t he p ackag e body . Th e pr eceding pack age is d if fer en t on ly w it h r espect t o t he placement of t he var iables NAME and MAJOR.

PACKAGE BODY students_pkg IS name VARCHAR2(100); major VARCHAR2(100); •

Table of Content s

Pr ogr am m ing Or a cl eprint_status ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on PROCEDURE (v_student_id IN VARCHAR2)

ISOwens By Kevin BEGIN Same code as above. Pub lish er: Prent ice Hall PTR END print_status; PROCEDURE print_major (v_student_id IN VARCHAR2) Pub Dat e: Decem ber 0 5, 2 003 ISI SBN: 0- 13 -0 850 33 -0 BEGIN Pages: 44 8 Same code as above. END print_major; END students_pkg; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d As w it h any lang uage, ex cessiv e u se of g lobal v ar iab les mak es t r acin g an d t rou blesh oot ing t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. dif ficult . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake You can d eclar e var iables in t he p ack age sp ecificat ion. Th e follow ing is a sim ple pack age t h at adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our w ill comp ile and st and on it s own w it hin an app licat ion en vir onm ent . I f t h e user SCOTT dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he com piles t his pack age t h en all of SCOTT's PL/ SQL pr ogr am s w ill be ab le t o r efer en ce t he st at e bu sin ess evolv es. Topics cov er ed include: of t his v ar iable or chan ge it at any t ime. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PACKAGE global_pkg ISit s and langu age f eat u res PL/ SQL p r ogr am un my_global_variable INTEGER := 0; END global_pkg; Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions You should en capsulat e t he global v ar iable w it h pr ocedu r es an d fun ct ion s t hat set and r et ur n I nt erof - prt ocess mush nicat t he value he v arcom iab le, ownions n ex t ( ref er t o Ch apt er 10 f or d iscussion of inf or mat ion hidin g) . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en tglobal_pkg , com plex datIS abases. PACKAGE PROCEDURE set_value(new_value INTEGER); [ Team LiB ] FUNCTION current_value RETURN INTEGER; END global_pkg; PACKAGE BODY global_pkg IS

my_global_variable INTEGER := 0; [ Team LiB ] PROCEDURE set_value(new_value INTEGER) IS BEGIN my_global_variable := new_value; END set_value; FUNCTION current_value RETURN INTEGER IS RETURN my_global_variable; BEGIN END get_value; END global_pkg;

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.9 Types 11.9.1 Boolean You can d eclar e a BOOLEAN PL/ SQL v ar iable t y pe. Ther e is no BOOLEAN dat abase colu mn t y pe. Boolean s ar e easy t o w or k w it h. Oft en t he ex ist ence of a value log ically r elat es t o a Boolean v ariab le. For t h e st udent 's d em o, a st udent can h ave sev er al m aj ors ( e. g ., Biolog y) . One valu eof is: Undeclar ed. Su ppose y ou con sid er Und eclar ed t o be FALSE and an y •v alid look up Table Content s ot ogr heram mmajing or Or t oa cl be equat es o: dhav Pr e ®TRUE. Tr i ggerLogically s and Stor et his d P roce dure s, tThir Ediing ti on a m aj or is TRUE. Hav ing an un declar ed m aj or is false. Such a scen ario can b e comm on in applicat ion code. By Kevin Owens I t h elp s t o h ave a pack age t h at m aps Boolean valu es t o a 1 an d 0. For exam p le, t h e follow ing pack age is a general pur p ose p ack age t hat t r ansfor m s a Boolean t o and f r om a zer o or on e. Pub lish er: Prent ice Hall PTR

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

CREATE OR REPLACE PACKAGE bool IS FUNCTION to_int (B BOOLEAN) RETURN NATURAL; NATURAL) BOOLEAN; Ef fectFUNCTION ively creat to_bool(N e an d man age com plexRETURN dat abases w it h Or acle! Sy st ems and dat ab ase ex per t END bool; Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. CREATE OR REPLACE PACKAGE BODY bool IS to_int RETURN UsingFUNCTION easy- t o- follow inst(B r uctBOOLEAN) ions an d ex am ples,NATURAL t his bookISpr esent s t echniq ues t o t ake BEGIN adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our THEN RETURN 1; ELSE END t oIF; dat ab asesIF to B incor por at e bu siness r ules RETURN w hich ar0; e easy man age and m odif y as t he to_int; bu sinEND ess evolv es. Topics cov er ed include: FUNCTION to_bool(N NATURAL) RETURN BOOLEAN IS BEGIN ViewIF in g N=1 constTHEN r aint sRETURN in t h e dat a dictELSE ion ar yRETURN FALSE; END IF; TRUE; END to_bool; Com plex r ule enf orcem en t END bool; PL/ SQL p r ogr am un it s and langu age f eat u res A d em on st r at ion of t he p r eceding pack age is a quer y t o g et t h e fir st m ajor fr om t h e Dat a t y pes and comp osit e st r u ct u re MAJOR_LOOKUP t able an d sav es a 1 or 0 using a DECODE st at em ent . The NATURAL num ber flag is conv ert ed t o a Boolean u sing t h e pack age. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e DECLARE NATURAL; Pr ogrmajor am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce a_declared_major for dat abase d ev elopers, BOOLEAN; d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly BEGIN int ellig en t , com plex dat abases. SELECT DECODE (major_desc, 'Undeclared', 0, 1) [ Team INTO LiB ] major FROM major_lookup WHERE ROWNUM = 1; a_declared_major := bool.to_bool(major);

END; [ Team LiB ]

11.9.2 Scalar Types You should declar e PL/ SQL var iable t y pes f r om t able colum n t y pes w henever p ossible. This m akes t h e code f lex ible. I t is also a for m of self - docum ent ing code. Th e follow ing pr oced ur e has one par am et er . I t is a v ar iable- leng t h st r ing .

PROCEDURE process(arg IN VARCHAR2); •

Table of Content s

Pr ogrnam Or a clur e ®e Tr s and Stor d P roce dure s,dThir d Edi onor e The exmt ing pr oced isi gger a sm all im preovem ent an uses atim

m ean in gfu l f orm al p ar amet er

nam e. Owens By Kevin

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

PROCEDURE process(state IN VARCHAR2); Pages: 44 8

This is b est becau se it sugg est s t hat t he par am et er passed is t o be a value wit h t h e dim ension of t h e STATE_D ESC colu mn in t he STATE_LOOKUP t able. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake PROCEDURE state_lookup.state_desc%TYPE); adv ant ag e ofprocess(state Or acle feat ur esIN such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: Ther e is no imp act on t he PL/ SQL code if t he dimension of t he STATE_DESC shou ld chan ge. I f t he colum n STATE_ DESC in t he t ab le STATE_LOOKUP is alt ered, t he PL/ SQL code w ill be in gb ut const in t hcom e dat a ed dicttion ar ying m any PL/ SQL pr ogr am s and chang in g t he r ecomView piled, t hisr aint is ms inor par o edit dim ension of a VARCHAR2 . Com plex r ule enf orcem en t As m ent ioned, t he use of % TYPE pr ov ides bu ilt - in docum ent at ion . The STATE_LOOKUP t able PL/ SQL p ns, r ogreach am un and langu age f eat tuhe res% TYPE m ak es it clear w h ich colum n v alue has t w o colum aritesVARCHAR2. Using t he pr ocedu re is ex pect ing. Dat a t y pes and comp osit e st r u ct u re Using % TYPE also aids t he pr ocess of im pact analy sis. Sup pose y ou w an t t o chang e t he Er rLOOKUP or han dling andThe except ions STATE_ t able. USER_ DEPEND ENCI ES view w ill show t his pr ocedur e as b eing depend en t on t he STATE_LOOKUP t ab le. Because t he p r ocedu re mer ely r efer en ces t he I nt er - pr ocess com mu nicat ions colum n w it h a % TYPE at t rib ut e, t he pr ocedu r e is for m ally dependent on t his t ab le. Using % TYPE w ill at eniv hance imr pact any t ime t o assess w hat code w ill, and be affect Declar e const aint s,analysis including p rim ar yyou k eyneed , u nique, f or eign k ey, ch eck m uched w it h amtor abele ch ange. Som comm PL/ SQL pr ed sefand ined St t yp t he g: it ion , is an inv aluable r esou rce Pr ogream m ingonOracle Tr igger ores ed in Prclud ocede ur es follow , Th ir dinEd for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ CHAR Team LiB ]

A CHAR v ar iable st or es a const ant - lengt h st r ing. An opt ional leng t h denot es t he num ber of b yt es w it h a m ax imu m of 32 767 by t es. Sub t yp es are STRI NG and CHARACTER.

variable variable

CHAR -– stores a single character. CHAR(10); -- stores 10 characters

The Oracle er ror ORA 650 2 is r aised if y ou assign a st r ing t hat exceed s t he dim ension of t h e CHAR var iable. Th is er r or ORA 65 02 is m apped t o an except ion VALUE_ERROR. Assig ning a st r ing less t h an t he dim ension r igh t p ads t h e var iable w it h blank s. Keep in m Table of Content s in d t hat you can righ t p ad a VARCHAR2 v ar iable w it h t he RPAD



ion.s and Stor e d P roce dure s, Thir d Edi ti on Pr ogr am m ing Or a cl e fu ® nct Tr i gger By Kevin Owens

Pub lish er: Pub Dat e: I SBN: Pages:

DECLARE C CHAR(3); Prent ice PTR X Hall VARCHAR2(30); Decem ber 0 5, 2 003 BEGIN 0- 13 -0 C 850:= 33 -0'ABCDE'; C := 'A'; 44 8

-- maximum of 3 characters

-- raises VALUE_ERROR -- C is: A and 2 blanks

X := RPAD('A', 3);

-- X is: A and 2 blanks, -- also X is equal to C

EXCEPTION Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t WHEN VALUE_ERROR THEN Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d dbms_output.put_line('Value error'); t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. END; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as tarig gers and st ored oced ur esf eat u rm esist hat allow y our VARCHAR2 A VARCHAR2 st ores v ariable leng t h st rpr ing . The m ax imu 40 00 by t es. dat ab ases t o incorMost por atdat e bu siness r ules w hich ar e easy t o man age and m odif y as t he a in a dat abase is char act er dat a. Use % TYPE w hen declar ing bu sin ess evolv es. PL/ Topics ed include: SQL cov v ar er iables t hat ar e popu lat ed w it h dat ab ase d at a. Ot herw ise use VARCHAR2. You can st or e lar ger char act er st ring s w it h t he CLOB dat at y pe. View in g const r aint s in t h e dat a dict ion ar y Ther e ar e m any st r ing fun ct ion s t hat supp ort m anipu lat ion of VARCHAR2 t y enf pes. See en Sect Com plex r ule orcem t ion 11 . 13, " St r ing Man ipulat ion Fu nct ions. " NUMBER Use NUMBER t o st ore fix ed or f loat ing- p oin t n um ber s. You specify t h e PL/ SQL p r ogr un it swand f eat pram ecision it h tlangu h e notage at ion : u res Dat a t y pes and comp osit e st r u ct u rescale)] NUMBER[(precision, Er r or han dling and except ions Pr ecision is t he t ot al num ber of d ecim al places. I nt er - pr ocess com is mut he nicat ions Scale n um ber of t hose p laces t o t he r ight of t he decim al p oin t . A scale can be n eg at ive. Th is indicat es sig nificance of digit s t o t h e lef t of t he Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch decimal point . I f y ou w ant t o st or e 5- d ig it n um bers and alway s st or e t h e m or e nu mb er rou nded t o h und r ed t hs, t he pr ecision is 3 and t h e scale is – 2. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d hEd , is an of inv99 aluable NUMBER(3,-2) This asit aion f or mat 900 . r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex Num dat ber abases. s ar e r ound ed t o fit t he p recision. A v alue t oo larg e w ill raise a VALUE_ ERROR ex cept ion . [ Team LiB ] To d eclar e a t yp e t est scor e t h at includ es t wo decimal places t o t he rig ht and w it h num b er s t h at r ang e fr om zer o t o 100 : NUMBER(5,2)

This h as a n um ber f orm at 999 .9 9.

[ Team LiB ]

NUMBER(3)

This st or es any t h r ee- digit w hole nu mb er .

NUMBER(1,-2)

This st or es 100 , 20 0, u p t o 90 0.

You can cont r ol rou nding w hen inser t in g v alues t o a NUMBER t y pe. Ther e ar e a v ar iet y of pow er f ul f unct ions: ROUND, TRUNC, CEI L, FLOOR. Refer t o Sect ion 11 . 15, " Nu mer ic Funct ions. " A D ATE t yp e st ores t h e DAY an d TI ME in a sing le var iable. Ref er t o Sect ion 11 .1 7, " D at e Funct ions, " f or DATE m anipu lat ion .

DATE

Use in t eg er - b ased num b er s w hen t her e is no fr act ional p art . Using a NUMBER t y pe t o st or e basic int eger s r eq uir es addit ional sp ace. NUMBER t y pes use f loat ing pr ecision t hat is un necessar y f or int eger v ar iables. •

Table of Content s

Pr ogr am m ing Or a cl e ® Use Tr i gger s and Stor s, ber Thirs. d Edi ti on PLS_INTEGER t his t o st or eedwPhroce oledure num The r ang e By Kevin Owens

is:

–2**31 to 2**31

BINARY_INTEGER This is an ot her int eger b ut perf or man ce is bet t er w it h PLS_I NTEGER Pub lish er: Prent ice Hall PTR t y pes. Pub Dat e: Decem ber 0 5, 2 003

POSITIVE

Use t his t o st or e n um ber s 1 and gr eat er . A VALUE_ERROR except ion is r aised if you assig n a nu mb er less t h an 1 .

I SBN: 0- 13 -0 850 33 -0

Pages: 44 8

NATURAL

Use t his t o st or e n um ber s zer o and gr eat er . A VALUE_ERROR ex cept ion is r aised if you assig n a nu mb er less t h an zer o.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t 11.9.3 Kevin OwRecords ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Record s ar e comp osit e st r uct u res t h at allow m ult ip le pieces of dat a t o be passed as a sin gle par ameasyet er . tRat her t han assions naman e, dbir d at e, and t o pr a esent pr ocedu re, p ass Using o- follow instpr uct ext ham ples, t hisage book s t echniq uesa tsingle o t aker ecor d w it hant t he nam e, bir t h as datte, e. st ored pr oced ur es- f eat u r es t hat allow y our adv agcom e ofponent Or acles:feat ur es such rigand gersag and dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he You ust evolv f irst es. declar e a recor t y pe definit ion; t hen declar e an obj ect of t hat t y pe. bu sinmess Topics cov erded include: You declar e t h e r ecor d t yp e w it h t he sy nt ax : View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res TYPE record_type_name IS RECORD( Dat a t y pes and comp osit e st r u[NOT ct u re NULL := expression], component_1 component_1_type component_2 component_2_type [NOT NULL := expression], Er r or hancomponent_3_type dling and except ions[NOT NULL := expression]); component_3 I nt er - pr ocess com mu nicat ions Com m on scalar com ponent t y pes include D ATE, NUMBER, and VARCHAR2. To declar e a Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch r ecor d t y pe using t hese scalar t yp es: m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. TYPE record_type IS RECORD( [ Team LiB ] name VARCHAR2(30), address VARCHAR2(30), birth_date DATE, age NUMBER(3));

[ Team LiB ] A r ecord com ponent t y pe can be d er ived fr om a colum n t yp e. For ex am ple:

TYPE record_type IS RECORD( name students.student_name%TYPE, major major_lookup.major_desc%TYPE);

You declar e a r ecor d st r uct u re b ased on t he r ecord t y pe. Th e recor d d eclar at ion com es aft er t he t yp e defin it ion . The f ollowin g d eclar es a r ecor d t y pe, t hen fet ches int o t hat r ecor d. Th e block ends wit h p rint in g t he com ponent s of t he r ecor d. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

DECLARE

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

TYPE record_type IS RECORD( I SBN: 0- 13 -0 850 33 -0 name students.student_name%TYPE, Pages: 44 8 major_lookup.major_desc%TYPE); major

student_rec record_type; BEGIN Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d SELECT t eaches you student_name, w hat y ou n eed t omajor_desc kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. INTO student_rec Using FROM easy- tstudents o- follow inst ions an d ex ambples, t his book pr esent s t echniq ues t o t ake a,r uct major_lookup adv ant ag e ofstudent_id='A101' Or acle feat ur es suchAND as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our WHERE a.college_major=b.major; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sindbms_output.put_line(student_rec.name); ess evolv es. Topics cov er ed include: dbms_output.put_line(student_rec.major); END; View in g const r aint s in t h e dat a dict ion ar y Comess plexr ecor r uled enf orcem ent st using a d ot t o r ef erence t h e comp onent s. For exam p le: You addr com pon en PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions student_rec.name := 'Ricky'; student_rec.major :=mu 'Biology'; I nt er - pr ocess com nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Record msorcan e b e assig ned t o one an ot her pr ov ided t hey ar e deriv ed f r om t he sam e r ecor d t y pe defin it ion . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Youdat can p reset def ault com ponent he tleader y pe d ef init ion. follow es tar uly for abase d ev elopers, d esign er s,v alues and prinojtect s look in g Th t o eb uild aning d mdeclar aint ain rint ecor d t y pe and pr eset s each comp onent value. All r ecord d eclar at ion s using t his t yp e hav e ellig en t , com plex dat abases. each com ponent init ialized t o t he cur r ent d ay and zer o, r espect ively . [ Team LiB ]

TYPE IS RECORD( [ Teamrecord_type LiB ] birth_date DATE := TRUNC(SYSDATE), age NUMBER(3) := 0);

The t yp e definit ion init ializes BI RTH_ DATE using t he b uilt - in fun ct ion SYSDATE. You can u se any f un ct ion , including y our PL/ SQL fu nct ion fr om an exist ing pack age. The id eal use of a r ecor d is t o redu ce par amet er s int o and out of pr ocedu r es. Consid er a fu nct ion t hat mu st r et ur n t he nam e an d college m ajor of a st ud en t . The f ollowin g illust r at es a simp le int erf ace t hat ev olv es wh en r ecor ds are used . The f un ct ion STUDENT ret ur ns a single r ecor d based on a pr im ar y k ey STUDENT_I D.



Table of Content s

Pr ogr am mOR ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, IS Thir d Edi ti on CREATE REPLACE PACKAGE students_pkg By Kevin Owens

TYPE student_type IS RECORD( name students.student_name%TYPE, major major_lookup.major_desc%TYPE); Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

FUNCTION student(ID IN students.student_id%TYPE) I SBN: 0- 13 -0 850 33 -0 RETURN student_type; Pages: 44 8

END students_pkg; CREATE OR REPLACE PACKAGE BODY students_pkg IS Ef fectFUNCTION ively creatstudent e an d man ageIN comstudents.student_id%TYPE) plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t (ID Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d RETURN student_type t eaches IS you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. r student_type; UsingBEGIN easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag eSELECT of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our student_name, major_desc dat ab ases t oINTO incorrpor at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er include: FROM students a,edmajor_lookup b WHERE student_id='A101' AND View in g consta.college_major=b.major; r aint s in t h e dat a dict ion ar y Com RETURN plex r uler; enf orcem en t END student; END students_pkg; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re The caller of t he p rocedur e can use t h e packag e fu nct ion in an assig nm en t st at em en t . The hancalls dlingt hand except pr ogr Er amr ort hat e fun ct ion ions can r ef er ence each com ponent w it hin an ex pr ession. The follow ing block m erely calls DBMS_OUTPUT t o pr int t he n ame an d maj or of a par t icu lar I ntst eru-dent pr ocess com college —sim ply mu by nicat r eferions en cin g t he r et ur ned record com ponent . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly BEGIN int ellig en t , com plex dat abases. dbms_output.put_line(students_pkg.student('A101').name); dbms_output.put_line(students_pkg.student('A101').major); [END; Team LiB ]

Record s can b e nest ed . A record com ponent can be anot h er recor d. A recor d com pon en t can

be a r ecor [ Team LiBd ]w hose t y pe is der ived fr om a dat ab ase t able r ow t y pe. For exam p le, t h e follow ing illust rat es a r ecor d w it h t w o com p onent s. The fir st is a st u dent I D ; t h e second comp onent is a r ecor d st ru ct u r e. The subcom pon en t nam es of STUDENT_AD VI SOR ar e t h e colu m n n ames of t he PROFESSORS t able. Th is cou ld st or e a st u dent I D and all r elev ant inf orm at ion abou t t h at st udent 's academ ic adv isor .

TYPE record_type IS RECORD( student students.student_id%TYPE, student_advisor professors%ROWTYPE);

The f ollow in g illust r at es code t h at cr eat es a t y pe w it h a com ponent fr om t he STUDENTS_PKG. •This n ew recor Table s pon en t s. The f irst is a st ud en t I D. Th e second com ponent is d hofasContent t w o com Pr ogr am m ing Or a cl e ® Tr i gger s and ion Stor in e d tPhe roce s, Thir Edi ti on ion. der ived fr om t h e t y pe declarat pdure ackag e spd ecificat By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

DECLARE I SBN: 0- 13 -0 850 33 -0 TYPE my_student_type IS RECORD( Pages: 44 8 ID VARCHAR2(10), student students_pkg.student_type); stud my_student_type; BEGIN Ef fectstud.ID ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t := 'A101'; Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. stud.student :=n eed students_pkg.student(stud.ID); dbms_output.put_line(stud.student.name); Using END; easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu ess com evolv es. Topics er ed include: A rsin ecord ponent can bcov e an index - by t ab le. Th e follow ing declar es an index - by t ab le t o cont ain st udent t est scor es. The r ecord t y pe d ef init ion has t w o com pon en t s: st ud en t I D and a st r uct ur e for t est scor es. A r ecor d st ru ct ur e, STUDENT_TEST_ SCORES, encapsulat es t he View in g const r aint s in t h e dat a dict ion ar y st udent and t ex t scores in t o a sing le st ru ct ur e. I n dex- b y t ables ar e cover ed in t he follow in g sect ion. Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re TYPE Er table_type NUMBER(3) INDEX BY r or han dlingIS andTABLE exceptOF ions BINARY_INTEGER; TYPE I student_test_scores_type nt er - pr ocess com mu nicat ions IS RECORD( student students.student_id%TYPE, Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch test_scores table_type); m or e student_test_scoure student_test_scores_type; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases.

11.9.4 %ROWTYPE [ Team LiB ]

You can d eclar e a r ecor d st r uct ur e based on t h e colu m ns of an exist ing t able. You do not declare a t y pe d ef init ion. Use % ROWTYPE w hen coding pr oced ur es and fu nct ions t h at per for m D ML on t ab les. A follow ing pr oced ur e adds a st ud en t an d h as one r ecor d par am et er .

[ Team LiB ]

CREATE OR REPLACE PACKAGE students_pkg IS PROCEDURE add_student(rec IN students%ROWTYPE); END students_pkg;

Add ressin g com pon en t s is t he sam e as a r ecor d. Th e r ecor d com pon en t n am es ar e t h e t able colum n n am es. Th e dat at y pe of each com pon en t is t he sam e t y pe as t h e colu mn in t he t able. The f ollow in g r efer ences t wo comp onent s in t he recor d.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

dbms_output.put_line(rec.student_id); By Kevin Owens dbms_output.put_line(rec.student_name);

lish er: Prent ice Hall m PTR ThePub STUDENTS t able u st exist b ef or e a r efer en ce t o st ud en t s % ROW TYPE w ill com pile. Pub Dat e: Decem ber 0 5, 2 003

Or acle Irecogn izes t h33 at-0t h e pack age is now dependent on t he STUDENTS t able. On e benefit t o SBN: 0- 13 -0 850 using % ROWTYPE and % TYPE is t he depend en cy infor m at ion you r et riev e fr om t h e Pages: 44 8 USER_D EPEND ENCI ES view .

11.9.5 Index-By Ef fect ively creat e an d Tables man age com plex dat abases w it h

Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tI eaches hataryeou n eed troained kn owind t oexbuild an u d res, comsimilar plex datt oabar ases f orThey y ourarbeusiness. ndex - byyou t abw les u nconst ed linrob er ust st r uct ray s. or iginally spar se. You can popu lat e t able p osit ion 20 and posit ion 30 using only t h e m em or y Using easyfollow r uct r eq uir ed f ort ot hose t w oinst slot s. ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o les incor at e bu siness ules hich ar e easy t o man age and m odif y as t he I ndex - by t ab ar por e const r uct ed w itr h t h ewfollow ing syn t ax: bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t TYPEtable_name IS TABLE OF component_type [NOT NULL] INDEX BY BINARY_INTEGER; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re For exam ple, t h e follow ing declar es a t able t y pe t h at can be u sed lat er t o d eclar e a t ab le of DATEEr t yrpe v ar iables. or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e TYPE date_table_type IS TABLE OF DATE INDEX BY BINARY_INTEGER; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Youellig canenconst r ain t he elem ent s t o NOT NULL w it h t h e sy nt ax: int t , com plex dat abases. [ Team LiB ]

TYPE IS TABLE OF DATE NOT NULL [ Teamdate_table_type LiB ] INDEX BY BINARY_INTEGER;

Com m on scalar com ponent t y pes include D ATE, NUMBER, and VARCHAR2. Th e follow ing declares an index - by t able. You r efer en ce t able elem ent s w it h par ent h eses enclosing an int eger or an y exp ression t h at ev alu at es t o an int eger .

DECLARE TYPE table_type IS TABLE OF INTEGER INDEX BY BINARY_INTEGER; tab table_type; •BEGIN Table of Content s Pr ogr am m ing Or a cl e1000; ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on tab(1) := tab(4) By Kevin Owens := 200; END; Pub lish er: Prent ice Hall PTR

A t able elem ent can r ecor d st ru ct u r e. Th e follow ing t able d ef init ion deriv es t he t able Pub Dat e: Decem ber 0be 5, 2a 003 elem ent fr om t h e STUD ENTS_PKG sh ow n in Sect ion 11 . 9. 3, " Recor ds. " For t h is cod e, each I SBN: 0- 13 -0 850 33 -0 t able element is a record st r uct ur e b ased on t he STUDENT_ TYPE r ecord of t he packag e. A Pages: 44 8 st udent r ecor d is fet ched using t he p ack age an d st or ed in t o t he t able at slot 1 01.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tDECLARE eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. TYPE table_type IS TABLE OF students_pkg.student_type UsingINDEX easy- tBY o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake BINARY_INTEGER; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat abtab asestable_type; t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: student_id students.student_id%TYPE := 'A101'; View in g const r aint s in t h e dat a dict ion ar y location binary_integer; BEGINCom plex r ule enf orcem en t location := am to_number(substr(student_id,2)); PL/ SQL p r ogr un it s and langu age f eat u res tab(location) := students_pkg.student(student_id); Dat a t y pes and comp osit e st r u ct u re dbms_output.put_line(tab(location).name); Er r or han dling and except ions dbms_output.put_line(tab(location).major); I nt er - pr ocess com mu nicat ions -- NO_DATA_FOUND Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch dbms_output.put_line('d'||tab(location+1).name); m or e dbms_output.put_line(tab(location).major); END; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int en t ,t ion comNO_ plexDATA_FOUND dat abases. is r aised if y ou read fr om a t able locat ion t o w hich no dat a Theellig ex cep has been assig ned. Th e NO_DATA_ FOUND ex cept ion is a m ot iv at ion f or eit her pack ing dat a in [ Team LiB ] seq uence and k eepin g t r ack of w her e t he d at a is locat ed or using t he b uilt - in t able at t r ibu t es. These at t r ibut es allow y our cod e t o sequence t h r ough spar se dat a beginnin g w it h t he FI RST and endin g w it h t he LAST element . You avoid r ead ing em pt y slot s wit h t h e EXI STS at t ribu t e. The b uilt - in at t r ib ut es ar e:

[ Team LiB ] Ret ur ns t he n um ber of locat ion s w it h dat a. COUNT Sm allest in t eg er locat ion cont aining d at a. FI RST Gr eat est int eger locat ion w it h dat a. LAST Ret ur ns t he int eg er t o t h e pr ior locat ion cont ainin g d at a. PRI OR Ret ur ns t he int eg er of t he nex t locat ion con t aining dat a. NEXT



Gu ard s against readin g em pt y cells. EXI STS Table of Content s

Pr ogr am m ing Or a cl e ® Tres i gger and Stor P roce durem s, em Thiror d Edi Delet ans elem ente dand fr ees y. ti on By KevinDELETE Owens

The f ollow in g illust r at es t able at t rib ut es. I f a t able is em pt y , FI RST an d LAST ev alu at e t o Pub lish Prent ice NEXT Hall PTRcan also r et u r n NULL. PRI OR evaluat es t o NULL if you pass an int eger NULL. PRIer:OR and ar gum hose ber v alu Pub ent Dat e:wDecem 0 5,e2is 003befor e t h e fir st t ab le index . PRI OR evaluat es t o NULL if you pass an int egerI SBN: ar gu0-ment w hose 13 -0 850 33 -0 v alue com es af t er t he last t able ind ex . Pages: 44 8

The f ollow in g b lock load s t w o slot s. The block in clu des DBMS_OUTPUT calls using NEXT and PRI OR. The v alue d isp lay ed is sh own as a comm ent nex t t o each PUT_LI NE call. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. DECLARE UsingTYPE easy-table_type t o- follow instIS r uctTABLE ions anOF d ex am ples, INDEX t his book esent s t echniq ues t o t ake INTEGER BY pr BINARY_INTEGER; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our tab table_type; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he BEGIN bu sintab(1) ess evolv es. Topics cov er ed include: := 1000; tab(4) := 200; dbms_output.put_line(tab.COUNT); View in g const r aint s in t h e dat a dict ion ar y FOR in r ule tab.FIRST..tab.LAST LOOP Com I plex enf orcem en t IF ptab.EXISTS(I) THEN PL/ SQL r ogr am un it s and langu age f eat u res dbms_output.put_line(tab(I)); Dat aELSE t y pes and comp osit e st r u ct u re dbms_output.put_line('no data in slot '||I); Er r orEND hanIF; dling and except ions END LOOP; I nt er - pr ocess com mu nicat ions dbms_output.put_line(tab.next(0)); -- 1 Declar at iv e const r aint s, including p rim ar y k-ey , null u nique, f or eign k ey, ch eck , and m uch dbms_output.put_line(tab.prior(0)); m or e dbms_output.put_line(tab.next(1)); -- 4 dbms_output.put_line(tab.next(2)); -- 4 Pr ogrdbms_output.put_line(tab.next(4)); am m ing Oracle Tr igger s and St or ed Pr oced ur , Th ir d Ed it ion , is an inv aluable r esou rce --esnull for dat abase d ev elopers, d esign er s, and pr oj ect leader dbms_output.put_line(tab.prior(5)); -- 4 s look in g t o b uild an d m aint ain t r uly int ellig END; en t , com plex dat abases. [ Team LiB ]

11.9.6 Varrays and Nested Tables

Wit hin PL/ a VARRAY is a const r ained arr ay st r uct ur e. I t s size is const r ain ed , w her eas [ Team LiBSQL, ] index - by t ables are u nbou nded. A VARRAY is cr eat ed w it h a m axim um dim en sion . You can d eclar e index - by t ab le t yp es and r ecor d t yp es in a packag e specif icat ion and declare pr oced ur es and fu nct ions t o oper at e on object s of such t yp es. Th is use of com posit e st r uct ur es en hances t he PL/ SQL code. I t m eans p rog r ams can pass a sin gle r ecor d w it h nest ed com ponent s, in clu ding nest ed ind ex - by t ables, rat h er num er ous par am et er s. You cannot st or e a r ecor d st r uct ur e or an index - by com posit e st r uct ur e as an obj ect in t he dat ab ase. How ev er , com posit e st r uct ur e obj ect s are sup por t ed. Th e follow ing illu st r at es t h e use of v ar ray s an d n est ed t ables. The f ollow in g d eclar es a VARRAY of nu mb er s an d uses t he const r uct or f unct ion t o init ialize v alues. Fir st t h e t y pe is def in ed . This is a VARRAY obj ect t yp e capable of st or ing up t o f our nu mb er s. Th en an obj ect , MY_NUMBERS, of t his t y pe is d eclar ed . The m ax imu m size is fou r, bu t less t han fou r nu mb er s can by assigned t o t h e v arr ay . COUNT is a bu ilt - in at t ribu t e t h at evalu at es t o t h e num ber of element s in t h e ar ray . Th e v arr ay ind ex ing st ar t s at 1 an d is •dense—t he ar Table s ed in sequence. r ay of is Content pop ulat Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

DECLARE Pub Dat e: Decem ber 0 5, 2 003 TYPE my_numbers_type IS VARRAY(4) OF NUMBER; I SBN: 0- 13 -0 850 33 -0 my_numbers my_numbers_type; Pages: 44 8 BEGIN my_numbers := my_numbers_type(1,2,3); FOR I IN 1..my_numbers.COUNT LOOP dbms_output.put_line(my_numbers(I)); Ef fectEND ivelyLOOP; creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin END; Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easyt o- follow inst uct an daex amle ples, pr esent o t ake if a Scien t if ic m easu rem en t s rar e ions seld om sing numt his ber book . A scien t ist wsillt echniq fin d it ues con tvenient adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat dat ab ase t able elem ent can b e an ( X,Y) coord inat e. St ar t w it h declaring a TYPE t hatallow y our dat asess tan o incor at edinat bu siness w hich mancreat age es and m odif as in t het h e r ep ab r esent ( X, Y)por coor e. Th er ules follow ing isarteheeasy DDLt ot hat such a tyy pe bu sin ess evolv es. Topics cov er ed include: dat ab ase. Th is is a n ew object y ou w ill find in USER_OBJECTS. The obj ect _ nam e is POI NT_TYPE and t h e obj ect _t yp e is TYPE. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res CREATE OR REPLACE TYPE point_type AS OBJECT ( Dat a t y pes and comp osit e st r u ct u re x NUMBER, yEr r or NUMBER); han dling and except ions I nt er - pr ocess com mu nicat ions The POI NT_ TYPE pr ovides a lot of f lex ibilit y. Prior t o t h is we wou ld lik ely cr eat e a r ecord const r aint s, including p rimcrar y ek ey nique, eign , and m duch st r uctDeclar ur e w itathiv( eX,Y) com ponent s and t hen eat an, u index - byf or t ab le t kypey, e wch it eck h t he r ecor t y pe or e en t st or ed in t h e t able. Cr eat ion of POI NT_ TYPE as an ob ject in t he d at abase w ill as t h emelem lead t o st or in g p oint s as sing le POI NT_TYPE en t it ies in t h e dat ab ase. We w on 't hav e t o cr eat e Pr amwmiting igger s and St or edn Pr oced ur esher , Th Ed ion , is inv aluable esou rce a togr able h a Oracle colum nTrfor X and a colum for Y. Rat , wired w illit cr eat e an a t able w it h a rcolum n for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly of t y pe POI NT_TYPE. Fur t her m ore, w e w ill shor t ly st or e an arr ay of p oin t s as a sin gle ent it y . int ellig en t , com plex dat abases. The f ollow in g PL/ SQL block declares a t yp e t hat is a VARRAY of element s w here each elem en t [is Team LiB ]TYPE. Th is t y pe is called POI NTS_VARRAY_TYPE. Th e v ariab le, POI NTS, is an a POI NT_ obj ect of t his t y pe. Th is is sim ilar t o t he p reced ing PL/ SQL block ex cept t hat t he v ar r ay consist s not of num ber s bu t ( X, Y) coor din at es.

POI NT_TYPE [ Team LiB ] is now an object in t he dat abase. Becau se POI NT_TYPE is now d ef ined in t h e dat ab ase, w e can declare a VARRAY t y pe of POI NT_TYPE elem ent s. We can also declare POI NT_TYPE v ariab les ( in t h e follow ing PL/ SQL block ) such as A_POI NT and PT.

DECLARE TYPE points_varray_type IS VARRAY(10) OF point_type; points points_varray_type := points_varray_type(); a_point point_type; pt point_type; BEGIN a_point := point_type(3,4); •

of Content s points Table := points_varray_type(point_type(1,2), point_type(2,3), a_point, By Kevin Owens point_type(5,4)); Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

FOR I IN 1..points.COUNT LOOP Pub lish er: Hall PTR ptPrent :=icepoints(I); Pub Dat e: dbms_output.put_line('x='||pt.x||' Decem ber 0 5, 2 003

y='||pt.y);

END LOOP; I SBN: 0- 13 -0 850 33 -0 END;

Pages: 44 8

We can creat e ad dit ional d at abase obj ect s u sin g t he exist ing POI NT_TYPE declarat ion . The follow ing creat es t w o mor e ob ject t y pes. The f ir st is a v ar r ay t y pe. The secon d is a nest ed Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t t able t yp e. Each of t h e follow ing t w o D DL st at em ent s cr eat es an ob ject in t he d at abase. Each Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d is depend en t on t h e ex ist ing dat abase ob ject , POI NT_TYPE. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin essOR evolv es. Topics covpoints_varray_type er ed include: CREATE REPLACE TYPE AS OF arpoint_type; View in g const r aint s in VARRAY(10) t h e dat a dict ion y CREATE OR REPLACE Com plex r ule enfTYPE orcempoints_nested_table_type en t AS OF age point_type; PL/ SQL p r ogr am un it s TABLE and langu f eat u res Dat a t y pes and comp osit e st r u ct u re I n rev iew , w e st ar t ed wit h a point t y pe, POI NT_TYPE, and a PL/ SQL- t yp e definit ion t hat r ort ohan dling and ionsof point s w it hin a PL/ SQL pr ogr am. The v ar ray and nest ed allow sErus m anipulat e aexcept VARRAY t able t yp es allow f or d at abase t able cr eat ion t o consist of colu mn s t hat consist of point I nt er - pr ocess com mu nicat ions ar r ays. Declar e const r aint s, y kaleymeasur , u nique, f or eign k ey, , and m uch The f ollow inat g iv t able is used t o including st or e env p ir rim onmarent ement dat a. Thechveck ar ray and nest ed t able m aror e eeach used t o illu st r at e t he dif fer en ces. The VARRAY colum n is st ored as pack ed d at a w it hin t he t able. Use a VARRAY for sm all am ount s of dat a for w hich y ou k now t he m ax imu m Pr ogr am m ing Oracle Tr igger s and St orereddat Praoced ur en es t,sTh ir d un Edkn it ion anensions. inv aluable r esou rce dim ension. Use nest ed t ables f or larg elem and ow,nisd im for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] CREATE TABLE environment_data (

NUMBER(3), [ sample_ID Team LiB ] points_varray points_varray_type, points_nested_table points_nested_table_type) NESTED TABLE points_nested_table STORE AS points_nested_tab;

The ENVI RONMENT_ DATA t ab le can n ow st or e an ar r ay of poin t s. An ar r ay of ( X, Y) point s can r ep r esent t he collect ion of dat a for a sin gle samp lin g. Th e follow ing PL/ SQL b lock d eclar es an obj ect based on t h e new ly cr eat ed d at a d ict ionar y t y pes. The t yp es POI NTS_VARRAY_ TYPE and POI NTS_NESTED_TABLE_TYPE enable u s t o cr eat e dat ab ase t ables w it h colum ns of each t y pe. Add it ion ally , w e can declare PL/ SQL v ariab les of t h ese sam e t y pes. The f ir st I NSERT st at em ent in ser t s a t w o- point ar ray for t h e v arr ay an d n est ed t able. Follow ing t h is init ial insert , t he v ar ray and nest ed t ab le st r uct u res ar e pop ulat ed wit h a ser ies of point s. The v arr ay h as fiv e poin t s; t he nest ed t able h as fou r point s. Th ese p oint ar r ay •st r uct ur es are Table Content t heofsecon d sin ser t . Followin g t hat , t h e st ru ct ur es are r ead fr om t h e dat ab ase Pr ogr am m ing Or a cl e ® Tr i gger and Stor s, ing Thir is d Edi w it h a SELECT st at em ent .s The k eyetdoPtroce h is dure w ork t h tieon t yp es t hat hav e been cr eat ed in t he dat ab ase; t hese sam e t yp es ar e u sed for dat abase colum ns an d PL/ SQL st r uct ur es. By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

DECLARE Pages: 44 8 a_points_varray points_varray_type := points_varray_type(); a_points_nested_table points_nested_table_type; BEGIN Ef fectINSERT ively creat e anenvironment_data d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t INTO Kevin Ow ens ex plor es PL/points_varray, SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d (sample_ID, points_nested_table) t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. VALUES (1, Using easy-points_varray_type t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle (point_type(3,4),point_type(3,5)), feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases tpoints_nested_table_type o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: (point_type(1,2),point_type(5,9)) ); View in g const r aint s in t h e dat a dict ion ar y a_points_varray := points_varray_type (point_type(1,2), Com plex r ule enf orcem en t point_type(2,3), point_type(7,3), PL/ SQL p r ogr am un it s and langu age f eat u res point_type(2,8), Dat a t y pes and comp osit e st r u ct upoint_type(5,4)); re Er r or han dling and except ions a_points_nested_table := points_nested_table_type (point_type(1,2), I nt er - pr ocess com mu nicat ions point_type(4,0), point_type(7,3), Declar at iv e const r aint s, including point_type(5,9)); p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e INSERT INTO environment_data Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce (sample_ID, points_varray, points_nested_table) for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly VALUES int ellig en t , com plex dat abases. (2, a_points_varray, a_points_nested_table); [ Team LiB ] SELECT INTO FROM WHERE

points_varray, points_nested_table a_points_varray, a_points_nested_table environment_data sample_ID = 1;

END; [ Team LiB ]

11.9.7 Objects The m at er ial in t his sect ion is based on t h e nest ed t ab le defined in t he pr ev iou s sect ion. You can b uild ob ject s, w it h m em ber fu nct ions, using t y pes y ou cr eat e. We cr eat ed t he t yp e POI NTS_NESTED_TABLE TYPE. This can be u sed as a dat abase t ab le colum n t y pe. I t can be used as a PL/ SQL var iable t y pe. We can cr eat e an ob ject f rom t his t y pe. Su ch an obj ect w ould be an ar r ay of point s w it h m em ber fu nct ions. A m ot iv at ion for t h is w ould be t h e need t o per for m f unct ions on t he ar r ay point s. For ex amp le, t here is a const ant need t o exam ine t he m inim um X coor din at e, max im um X coord in at e, and av er age point . Th e follow ing creat es an obj ect t y pe. This is lik e t he specificat ion of t he obj ect . I t declares m emb er fu nct ions. The bod y is a secon d par t . •

Table of Content s

Pr ogrD am m ing Oreat a cl ee® t Tr i gger s andisStor e dfollow P roce dure The DL t o cr his ob ject the ing.s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

CREATE OR REPLACE TYPE points_object_type AS OBJECT I SBN: 0- 13 -0 850 33 -0 ( Pages: 44 8 points_nested_table_type, points MEMBER FUNCTION sample_size RETURN NUMBER, MEMBER FUNCTION point_text RETURN VARCHAR2, Ef fectMEMBER ively creat e an d man age com plex NUMBER, dat abases w it h Or acle! Sy st ems and dat ab ase ex per t FUNCTION min_x RETURN KevinMEMBER Ow ens FUNCTION ex plor es PL/ SQL, Or acle's NUMBER, answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d max_x RETURN t eaches you wFUNCTION hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. MEMBER avg_x RETURN NUMBER, MEMBER FUNCTION best_point RETURN point_type, UsingMEMBER easy- t ofollow inst radd_to(v uct ions an dpoint_type) ex am ples, t his book pr esent s t echniq ues t o t ake procedure adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our ); dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: The ob ject b ody is cr eat ed w it h t he f ollow ing . View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res CREATE OR REPLACE TYPE body points_object_type AS MEMBER FUNCTION sample_size RETURN NUMBER IS Dat a t y pes and comp osit e st r u ct u re BEGIN points.count; Er r orRETURN han dling and except ions END sample_size; MEMBER FUNCTION point_text I nt er - pr ocess com mu nicat ions RETURN VARCHAR2 IS s at varchar2(1000); Declar iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch BEGIN m or e FOR i IN 1..points.COUNT LOOP Pr ogr am m ing Oracle igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce s := sTr|| '('||points(i).x||','||points(i).x||')'; for dat abase elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly ENDd ev LOOP; int ellig en tRETURN , com plex s;dat abases. END point_text; [ Team LiB ] FUNCTION min_x RETURN NUMBER MEMBER IS result NUMBER := null; BEGIN

FOR [ Team LiB ] i IN 1..points.COUNT LOOP result := least(nvl(result,points(i).x),points(i).x); END LOOP; return result; END min_x; MEMBER FUNCTION max_x RETURN NUMBER IS result NUMBER; BEGIN FOR i IN 1..points.COUNT LOOP result := greatest(nvl(result,points(i).x),points(i).x); END LOOP; return result; END max_x; • Table of Content s MEMBER FUNCTION avg_x RETURN NUMBER Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on IS By Kevin Owens result NUMBER := 0; BEGIN FOR i IN 1..points.COUNT LOOP Pub lish er: Prent ice Hall PTR result := result + points(i).x; Pub Dat e: Decem ber 0 5, 2 003 END LOOP; I SBN: return 0- 13 -0 850 (result/points.count); 33 -0 END avg_x; Pages: 44 8 MEMBER FUNCTION best_point RETURN point_type IS pt point_type; BEGIN Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t pt := point_type(points(1).x,points(points.COUNT).y); Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d RETURN t eaches you w hat pt; y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. END; procedure ISbook pr esent s t echniq ues t o t ake UsingMEMBER easy- t ofollow inst radd_to(v uct ions an dpoint_type) ex am ples, t his BEGIN adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab asespoints.EXTEND; t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he points := v; bu sin ess evolv es. (points.count) Topics cov er ed include: exception when others then points := points_nested_table_type(v); Viewadd_to; in g const r aint s in t h e dat a dict ion ar y END END; Com plex r ule enf orcem en t ogrions am un and en langu age tf eat The mPL/ emSQL ber pfur nct ar it e sf requ t ly shor an u d res sim ple. They only op er at e on a nest ed t able st r uct ur e consist in g of a ser ies of ( X, Y) poin t s. Building t he mem ber f unct ions in t o t h e obj ect Dat ce a t yt he pessize andand comp ositlex e stitryu of ct utre can redu comp h e applicat ion cod e. Th e follow ing PL/ SQL b lock illust rat es a new ENVI RONMENT_D ATA t ab le. I n t his t ab le, t he colum n is not a nest ed t able, Er r or han dling and except ions bu t r at her an obj ect of t y pe POI NTS_OBJECT_ TYPE. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e CREATE TABLE environment_data Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce ( for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly sample_ID NUMBER(3), int ellig en t , com plex dat abases. points_object points_object_type) NESTED TABLE [ Team LiB ] points_object.points STORE AS points_object_tab;

The f ollow in g PL/ SQL block declares an obj ect of t y pe POI NTS_OBJECT_TYPE. Met hod s ar e

used t o LiB pop]ulat e an d select fr om t h e object . Th e fir st m et hod used is AD D_TO. This ext en ds [ Team t he nest ed t able b y addin g a point . Fou r poin t s ar e added t o t he obj ect . An I NSERT st at em en t add s t he ob ject t o t he d at abase t ab le. Th e obj ect is select ed fr om t he t able, b ack in t o t h e or iginal ob ject d eclar at ion . The calls t o DBMS_OUTPUT p rin t 2, 8, an d 5 . 75 for t he m in, m ax , and av er ag e valu es r espect iv ely . The BEST_POI NT m et hod ev alu at es t o t h e m inum um X and m ax im u m Y coord inat e an d p rin t s X= 2 Y= 3 .

DECLARE point_obj points_object_type := points_object_type(points_nested_table_type()); • Table ofpoint_type; Content s best_point Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on BEGIN point_obj.add_to(point_type(2,3)); By Kevin Owens point_obj.add_to(point_type(6,1)); point_obj.add_to(point_type(7,3)); Pub point_obj.add_to(point_type(8,3)); lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

INSERT points_object) I SBN: 0- INTO 13 -0 850environment_data(sample_ID, 33 -0 VALUES Pages: 44 8 (1, point_obj); SELECT points_object INTO point_obj Ef fectFROM ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t environment_data KevinWHERE Ow ens sample_ID ex plor es PL/=SQL, 1; Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. dbms_output.put_line(point_obj.min_x); Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake dbms_output.put_line(point_obj.max_x); adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dbms_output.put_line(point_obj.avg_x); dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he best_point := point_obj.best_point; bu sin ess evolv es. Topics cov er ed include: dbms_output.put_line y='||best_point.y); View('x='||best_point.x||' in g const r aint s in t h e dat a dict ion ar y END; Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res

11.9.8 Large Objects (LOBs)

Dat a t y pes and comp osit e st r u ct u re Lar ge object s r efer t o wh ole docum ent s or im ages t h at n eed t o b e st or ed as colum n valu es in Er r Em or han andogexcept a t able. ploydling ee phot rap hicions im ages ar e ex am ples of colum n v alues in an em ploy ee dat ab ase. Th ese b in ar y gr aphic im ages ar e n ot m anipu lat ed b ut y ou can u se PL/ SQL t o read I ntfrerom - pr on ocess coman mudnicat im ages e t able st or eions int o anot h er . You can load im ages f rom host f iles in t o a dat ab ase t able. Binar y im ages ar e st ored as a BLOB in t h e dat abase. The BLOB is also a Declar at iv e const s, including riminart yhek ey u nique, k ey, cheeck andamPL/ uch PL/ SQL t yp e. Char act err aint object s ar e st orped d at, abase asf or a eign CLOB. Ther is ,also SQL m or e CLOB t y pe. A BFI LE is a dat ab ase and PL/ SQL t y pe u sed t o refer ence a f ile. All man ip ulat ion of lar ge obj ect s is t hr ough t h e Or acle DBMS_LOB p ack age. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for abase ev elopers, esign erios,inand pr ojaect leader s lookt oinst g or t oeblar uild d mact aint Thedat f ollow in gdillust r at es adscenar wh ich t able is used gean char er ain t r uly int ellig en t , com plex dat abases. docum ent s. Th e docum ent is t he DOC colum n. The I D colu mn is a pr imar y k ey used t o ident if y a d ocu ment . [ Team LiB ] The t able t o st or e d ocu ment s is:

[ Team LiB ] CREATE TABLE doc ( doc_id NUMBER(5) PRIMARY KEY, document CLOB );

We st ar t w it h insert in g an em pt y d ocu m en t using t h e Or acle b uilt - in fun ct ion EMPTY_CLOB. Lat er , t h e em p t y docum ent can be ref er enced in PL/ SQL. This w ill r equir e d eclar in g a CLOB t y pe ob ject t h at act s lik e a poin t er t o t h e emp t y docum ent . To insert t he em pt y docum en t ( using 1 for t his DOC I D. )



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

INSERT INTO DOC (doc_id,document) VALUES (1, empty_clob()); COMMIT; Pub lish er: Prent ice Hall PTR Datte:he Decem bert o 0 5,load 2 003host f iles in t o t h e DOC t able. Assum e t he host f iles ar e lar ge ConPub sider need I SBN: 013 -0 850 33 -0 char act er docum en t s and ex ist in a host d irect or y called D:\DOCS. Pages: 44 8

We d o not use h ost dir ect or y p at hnam es in t he code. Or acle m aint ains log ical t o ph ysical m appin gs in t he v iew DBA_D I RECTORI ES. You m ust cr eat e t he log ical conn ect ion w it h a CREATE DI RECTORY st at em ent . Af t er t hat , you code u sin g t h e logical nam e. Cr eat e a dir ect or y increat t he edat it h tcom he f plex ollowdat in g.abases w it h Or acle! Sy st ems and dat ab ase ex per t Ef fect ively anabase d manwage Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CREATE OR REPLACE DIRECTORY SAMPLE_DOCS AS 'D:\DOCS'; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: To d o t h is you n eed t he CREATE ANY D I RECTORY p riv ilege. View in g const r aint s in t h e dat a dict ion ar y Assu m e you w ant t o load t h is file int o t he D OC t able: Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re users_manual.pdf Er r or han dling and except ions The f ollow I nt er in - prg ocess PL/ SQL com block mu nicat usesions t he PL/ SQL fu nct ion BFI LENAME t o r efer en ce t he file cont ent . BFI LENAME est ab lish es t he v ariab le THE_BFI LE as a r efer en ce t o t h e file. Aft er t he Declar at iv e tconst r aint including ar yedk ey , ugnique, or eign k ey,ofch1 eck , and BFI LENAME call, he em pt y s, d ocu ment isp rim select u sin t h e prf im ary key fr om t hem uch m orgeI NSERT st at em en t . Bot h t he CLOB and BFI LE ar e accessed in a man ner sim ilar t o pr ecedin t he way a poin t er ref er ences mem or y. The cont ent is not phy sically local t o t he p rocedur e. I t Pr am m ing and Oracle Tr iggertshrand Pr ocedLOB ur espackag , Th ir des. Ed Th it ion , is anFROMFI inv aluable r esou is ogr r ef erenced accessed oug St h tor heedDBMS_ e LOAD LE cop ies rce t he for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t uly cont ent . Then b ot h ref er ences are closed . At com plet ion, t he host file cont ent exist s in trhe int ellig enle. t , com plex dat abases. DOC t ab [ Team LiB ]

DECLARE [ Team LiB ] the_bfile BFILE; the_clob CLOB; bfile_size PLS_INTEGER; clob_size PLS_INTEGER; v_directory VARCHAR2(30) := 'SAMPLE_DOCS'; v_filename VARCHAR2(30) := 'users_manual.pdf '; BEGIN the_bfile := BFILENAME(v_directory, v_filename); SELECT document INTO the_clob FROM doc WHERE doc_id = 1 FOR UPDATE OF doc.document NOWAIT; -- open the clob for update. dbms_lob.open(lob_loc => the_clob, open_mode => dbms_lob.lob_readwrite);



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

-- open the bfile

By Kevin Owens dbms_lob.fileopen

(file_loc => the_bfile, open_mode => dbms_lob.file_readonly);

Pub er: Prent ice the Hall PTR --lishwhat is size

of the bfile

Pub Dat e: Decem ber 2 003 bfile_size :=0 5,dbms_lob.getlength(the_bfile); I SBN: 0- 13 -0 850 33 -0

-load Pages: 44 8 from file dbms_lob.loadfromfile (dest_lob => the_clob, src_lob => the_bfile, amount => bfile_size); Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t load. Kevin-Owcheck ens exsize plor esafter PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d clob_size := dbms_lob.getlength(the_clob); t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. close file inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake Using-easyt o- follow dbms_lob.fileclose(file_loc => gers the_bfile); adv ant ag e of Or acle feat ur es such as t rig and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he blob bu sin-essclose evolv es. Topics cov er ed include: dbms_lob.close(lob_loc => the_clob); View in g const r aint s in t h e dat a dict ion ar y commit; END; Com plex r ule enf orcem en t PL/ SQL ogr am it ss and langu age f eatand u respr int s it using DBMS_OUTPUT. Use a sm all The f ollow in gpbr lock ex tun r act t he CLOB obj ect file f or t his ex ercise. CLOBs are not in t en ded t o be pr int ed u sin g D BMS_OUTPUT. The Oracle Dat afut ynct pes and ositlin e st u ctt his u reb lock , r eplaces a line f eed w it h a dash. Ot her wise, REPLACE ion, in comp t he last e rof DBMS_ OUTPUT pr int s t h e fir st line. This scr ipt r eads t he fir st 2 00 char act er s of t h e CLOB Er r or han dling and except ions st or ed in t he D OC t able. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e DECLARE Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce the_clob for dat abase d ev elopers,CLOB; d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly clob_size PLS_INTEGER; int ellig en t , com plex dat abases. max_size PLS_INTEGER := 200; amount_to_read PLS_INTEGER; [ Team LiB ] offSet PLS_INTEGER:= 1; vbuf VARCHAR2(200) := null; BEGIN SELECT document INTO the_clob FROM doc WHERE doc_id=1;

[ Team LiB ] dbms_lob.open(the_clob, dbms_lob.lob_readonly); clob_size := dbms_lob.getlength(the_clob); amount_to_read := least(clob_size, max_size); dbms_lob.read(the_clob, amount_to_read, offset, vbuf); dbms_lob.close(the_clob); dbms_output.put_line(replace(vbuf,chr(10),'-')); END;

This w ill p rint t h e fir st 20 0 ch aract er s of t he CLOB, w h ich y ou load ed f rom a BFI LE, and w hich • Table of Content s y ou f ir st r ead w it h BFI LENAME. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

[ByTeam Kevin Owens LiB ]

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.10 IF Statement The I F const r uct imp lem ent s I F- THEN- ELSE log ic w it h op t ional ELSI F clau ses.

11.10.1 Simple IF The sim ple I F st at em en t per for m s an act ion b ased on a t r ue- f alse cond it ion, illust r at ed by t he diam ond in Figur e 11 - 1. I f t he con dit ion ev aluat es TRUE, t he code ex ecut es t he logic in t he box . •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d Prroce s, .Thir d Edipl ti on Figu e 1dure 1 -1 Sim e

I F.

By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

An ex am ple is: Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using t o- THEN follow binst d ex am ples, t his book pr esent s t echniq ues t o t ake IF (a easy< 10) :=r uct 1;ions ENDanIF; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

11.10.2 If-Then-Else

in gELSE conststr aint s in t,hshow e datna in dictFigur ion ar An I F-View THENat ement e y11 - 2, p er f orm s an act ion based on a t r u e- f alse condit ion. An alt er nat iv e act ion is alw ay s per for m ed. I f t he t est ev aluat es TRUE, t he code Com plex r ule enf orcem en t execut es t h e logic in t hat box , ot her w ise it ex ecut es t he log ic in t h e ot her b ox. PL/ SQL p r ogr am un it s and langu age f eat u res

Figu r e 1 1 -2 . I f -Th en -El se .

Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team An ex amLiB ple] is:

[ Team LiB ] IF (a < 10) THEN b := 1; ELSE b := 20; END IF;

11.10.3 If-Then-Elsif with Else The I F- THEN- ELSI F- w it h - ELSE const r uct is show n in Figur e 11 - 3. An y TRUE cond it ion w ill execut e code in t h at b ox and exit t he const r uct . A FALSE con dit ion ent er s t h e nex t decision . The log ic in t h e ELSE p art execut es if no con dit ion is TRUE.

Figu r e 1 1 -3 . I f -Th en -El si f w it h El se .



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

I n t his exam p le, B is set t o 3 if no condit ion ev er evalu at es t o TRUE Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our IF (a < e10) THEN dat abbases o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he := t1; bu sin ess es. THEN Topics cov er ed include: ELSIF (aevolv = 11) b := 2; ELSE g const r aint s in t h e dat a dict ion ar y bView := in3; END IF; Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Mu lt ip le con dit ions m ay b e t r ue, bu t t h e logic of t he fir st TRUE con dit ion is ex ecu t ed , only . The f ollow I F st at em ent osit b egeins it h assign ing A t h e valu e of 8. Th e fir st t est is TRUE, so is Dat a in t ygpes and comp st r w u ct u re t he second. Aft er t h is I F st at em ent , B is equal t o 1. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch a := m8; or e IF (a < 10) THEN Pr ogrbam:= m ing 1; Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce ELSIF (a < d20) THEN d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly for dat abase ev elopers, int ellig b en :=t , 2; com plex dat abases. ELSE [ Team LiB3; ] b := END IF;

[ Team LiBIf-Then-Elsif ] 11.10.4 No Else The I F- THEN- ELSI F- No- ELSE const ru ct , show n in Figur e 11 - 4, of fer s anot h er opt ion w it h I F st at ement s. Any TRUE con dit ion w ill ex ecu t e code in t hat box an d ex it t h e con st ru ct . Each decision failur e ent er s t h e next decision. I f all t est s ev aluat e t o FALSE, n o logic is ex ecut ed . This is sign if ican t ly dif ferent f rom I F st at em ent s t h at u se an ELSE clau se.

Figu r e 1 1 -4 . I f -Th en -El si f No Else.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

This ex am ple does not assig n a v alu e t o B if t he t est cond it ions f or A ar e each f alse. Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d IF (a Ow < ens 10) ex THEN t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. b := 1; ELSIF (a = 11) THEN Usingb easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake := 2; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our END IF; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

11.10.5 Statement Expressions View in g const r aint s in t h e dat a dict ion ar y The I F sy nt ax in clud es an op t ional ELSI F and ELSE clause. Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re IF (multiline BOOLEAN expression) THEN Er r or han dling and except ions Statement; Statement; I nt er - pr ocess com mu nicat ions ELSIF (multiline BOOLEAN expression) THEN Statement; Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Statement; m or e ELSIF (multiline BOOLEAN expression) THEN Pr ogrStatement; am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Statement; int ellig en t , com plex dat abases. ELSE Statement; [ Team LiB ] Statement; END IF;

The f ollow [ Team LiBin]g is a simp le I F st at em ent . Th is I F- THEN- ELSE st at ement assig ns a value t o B for all v alues of A. An I F st at em ent can b e coded in such a m anner t h at it ov er looks som e condit ions. Som et im es t his is int end ed . Som et im es it is a bu g.

IF (a < 10) THEN B := 1; END IF;

The p r ev ious I F st at em en t on ly con sider s t h e case w h er e A is less t han 1 0. Th is next st at ement t ak es an act ion on B f or any v alue of A.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

IF (a Owens < 10) THEN b := 1; ELSE b := 2; END IF; By Kevin An IPub F st ater: emPrent enticecan se t he PL/ SQL NULL st at em en t t o indicat e t h at all cond it ions ar e being lish HalluPTR considered. For ex am ple, t he f ollowin g I F- THEN- ELSE con t ains a PL/ SQL NULL st at em ent t o Pub Dat e: Decem ber 0 5, 2 003 exp licit ly st at e t h at n o act ion is t o be t aken if A is gr eat er t han 1 0. I SBN: 0- 13 -0 850 33 -0

Pages: 44 8

IFfect Ef (aively = 10 AND A < 20) THEN I SBN: 0- 13 -0 850 33 -0 B := 2; Pages: 44 8 ELSIF (A = 225) THEN B := 3; ELSE B := 4; Ef fectIF; ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t END Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Redu ce an d elim inat e t h e t y pe of logic show n by p er f orm ing t h e t r ansfor m at ion wit h in t h e Using o- follow ions an dhow ex am ples,CASE t his book pr en esent s tfor echniq t o t ake SQL queasyer y . tThe followinst in gr uct illust r at es a SQL st at em t p er m s t hues e equiv alen t adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat allow y our t r ansfor m at ions u sed in t he p rev iou s I F st at ement s. dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y CREATE TABLE TEMP (A NUMBER(2)); Com plex r ule enf orcem en t INSERT INTO TEMP VALUES (11); PL/ SQL p r ogr am un it s and langu age f eat u res DECLARE BDat INTEGER; a t y pes and comp osit e st r u ct u re BEGIN SELECT CASE Er r or han dling and except ions WHEN A < 10 THEN 1 WHENcom A >= AND I nt er - pr ocess mu 10 nicat ionsA < 20 THEN 2 WHEN A = 225 THEN 3 END DeclarBatFROM iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch INTO TEMP; m or e dbms_output.put_line('B='||b); END; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig enement t , comsplex abases.t ran sf or m v alues w hen t he dat a is select ed f rom t he d at abase. SQL st at w it hdat D ECODE The f ollow in g SQL quer ies t h e college m aj or descr ipt ion s fr om t h e MAJOR_LOOKUP t able. [Wit Team LiB quer ] hin t he y each m ajor descr ipt ion is t r ansfor m ed t o an alt er nat iv e st r ing.

[ Team LiB ] SELECT DECODE ( major_desc, 'Undeclared' 'Biology' 'Math/Science' 'History' 'English' FROM major_lookup;

, , , , ,

'A1', 'A2', 'A3', 'A4', 'A5') major

The SQL CASE ex pr ession is m ore p ow er f ul t h at D ECOD E. Use CASE and DECODE t o in it ially t r ansfor m d at a. This sim plifies t h e PL/ SQL logic. [ Team LiB ] •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.11 CASE Statement Case st at em en t s im plem ent t he sam e const r uct m odel as I F- THEN- ELSI F w it h ELSE const r uct s. The CASE st at em en t is easier t o r ead an d h as im pr oved per for m ance ov er com plex I F st at em ent s. Ther e ar e t w o f or ms t o t h e CASE st at em ent : Searched Case St at em en t Case w it h Select or •

Table of Content s

11.11.1 Searched CASE Statement

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

The sear ch ed CASE st at em en t ev alu at es a sequence of t est cond it ion s. When a t est ev alu at es t o TRUE, code is ex ecut ed and t h e con st ru ct is com plet e—n o f ur t her condit ion s are ex am ined. Pub lish er: Prent ice Hall PTR Pubt ion Dat e:f alls Decem 0 5,ELSE 2 003 clause if no pr ior condit ions are met . Th e ELSE clause can be any Ex ecu t ober t he gr oup of st at t s33or-0 t h e NULL st at em ent . NULL st at ement s r ef er t o t h e PL/ SQL st at em en t , I SBN: 0-em 13 -0en 850 NULL. Pages: 44 8

I f no con dit ion is met and t her e is no ELSE clause, an ex cept ion is r aised . The er r or is: Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ORA-06592: CASE not found while executing CASE statement. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat t o incor por at siness w hich Thisaberases r or can b e capt ureedbuwit h t h er ules ex cept ion: ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t CASE_NOT_FOUND PL/ SQL p r ogr am un it s and langu age f eat u res This isDat illust edand lat ercomp . Theosit Sear a t yr at pes e stched r u ct uCase re St at ement evaluat es an ex pr ession w it h each WHEN clau se. Th e syn t ax is t he f ollowin g: Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch CASE m or e WHEN expression THEN action; Pr ogrWHEN am m ing Oracle Tr igger St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce expression THENs and action; for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly WHEN expression THEN action; int ellig en t , com plex dat abases. [ELSE action;] END CASE; [ Team LiB ] The f ollow in g ex am ple defin es a r ule f or set t in g a v alu e t o B based on t h e valu e of A. We im plem ent t his r ule w it h a CASE st at em ent .

[ Team LiB ] A

B

A < 10

1

10 >= A < 20

2

225

3

All other values

4

The CASE st at em ent for t h is is:



Table of Content s

CASE Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on WHEN (A < 10) THEN B := 1; By Kevin Owens WHEN (A >= 10 AND A < 20) THEN B := 2; WHEN (A = 225) THEN B := 3; ELSE B := 4; lish er: Prent ice Hall PTR ENDPub CASE; Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

The ELSE clau Pages: 44 8se is opt ional. Th e follow ing CASE st at ement is v alid ; h owev er , t his code r aises an ex cept ion becau se no cond it ion is TRUE. The ex cept ion han dler cat ch es t he er ror and pr int s t he v alue A. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. DECLARE Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake A ag INTEGER := 300; adv ant e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our BEGIN dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sinCASE ess evolv es. Topics cov er ed include: WHEN (A < 10) THEN B := 1; WHEN (A >= 10 AND A < 20) THEN B := 2; (A r=aint 225) THEN ViewWHEN in g const s in t h e dat a dict ion ar y B := 3; END CASE; EXCEPTION Com plex r ule enf orcem en t WHEN CASE_NOT_FOUND THEN PL/ SQL p r ogr am un it s and langu age f eat u res dbms_output.put_line('A = '||a); END; Dat a t y pes and comp osit e st r u ct u re Er r or sthan dling except The CASE at em ent and is easier t oions r ead in t h e code. Com par e t h e follow ing CASE logic w it h t he sam e I F log ic. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] Se a rch Ca se St at em e nt CASE WHEN (A SELECT substr('12345',-1)||substr('12345',1,1) str FROM dual; STR --51

START_ POS an d NO_ OF_CHARS can b e an ex pr ession. This exam p le uses t he I NSTR f un ct ion •for t he START_POS Table of Content value. sTh e obj ect iv e is t o select t he f ile nam e por t ion fr om a fu ll Pr ogr am m ing Or a cl e ® Tr s and e dnP roce Thir dion Ediof ti on pat h nam e. Fir st , u se iIgger NSTR t o Stor r et ur t he dure last s,posit a for w ar d slash in a st r ing . I n t his exam t h e posit ion of t he last f orw ar d slash is t he 10t h char act er posit ion. By Kevinple, Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

SQL> SELECT instr('/aa/bb/cc/dd','/',-1,1) Pages: 44 8

FROM dual;

INSTR('/AA/BB/CC/DD','/',-1,1) -----------------------------10 Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tTo eaches ou ame n eedfrtom o knaow build rob ust an d all com plex dat ab ases selectyou ju stwthat he fyilen fullt opat hn ame, select r em aining char actf or er sy our af t erb usiness. t he last for w ar d slash—f or t h e pr ev ious select , t hat wou ld b e all char act er s af t er t he 1 0t h posit ion. Using easyinsttrouct ions an d ex book pr esent s t echniq This can be tgoenfollow er alized t he ev aluat ionam of:ples, t he tIhis NSTR fu nct ion r esult p lusues 1. t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat abpor ases por at e bu hich f ar e easy t o man ageces anda m y ast hat t he can I ncor at et o" Iincor NSTR r esult + siness 1" in t or ules a PL/wSQL unct ion. This pr odu fuodif nct ion es. e Topics covof er aedp at include: rbu etsin ur ness t heevolv f ilenam por t ion hn ame. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t FUNCTION filename(v_path IN VARCHAR2) RETURN VARCHAR2 PL/ SQL p r ogr am un it s and langu age f eat u res IS BEGINDat a t y pes and comp osit e st r u ct u re RETURN substr(v_path, instr(v_path,'/',-1,1)+1); END filename; Er r or han dling and except ions I nt er - pr ocess com mu nicat ions User s of t his f un ct ion can ex t r act t h e filenam e por t ion of a st r ing by coding : Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly my_file_name := filename(v_full_pathname); int ellig en t , com plex dat abases. my_file_name := filename('dir/dir/filename.dbf'); [ Team LiB ] I f t he v alue p assed, V_ FULL_PATHNAME does not cont ain a f orw ar d slash ( a caller passed a filenam e only ) and I NSTR r et ur ns a 0. To t his 0 is add ed a 1. Th is ev aluat es t o t he f ollowin g:

[ Team LiB ]

RETURN substr(v_path, instr(v_path,'/',-1,1)+1); RETURN substr(v_path, 0+1);

The f un ct ion RETURN v alu e is t he orig in al st r in g, w h ich w ould be t h e file nam e. SUBSTR r et ur ns NULL if t he START_POS ex ceeds t he lengt h of a st rin g. This can occu r if y ou code a SUBSTR fu nct ion wit h a lit er al START_ POS v alue. Th e follow ing ex am ple uses 10 . I f t he arg um en t p assed t o t h is pr oced ur e is less t h an 1 0 ch aract er s, t he SUBSTR fun ct ion r esu lt is NULL. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

PROCEDURE test (arg IN VARCHAR2) IS declarations Pub lish er: Prent ice Hall PTR BEGIN Pub Dat e: Decem ber 0 5, 2 003 my_variable I SBN: 0- 13 -0 850:= 33 -0SUBSTR(arg, 10); remaining PL/SQL Pages: 44 8 END

The p r ocedu re TEST m ay n ot pr od uce t he ex pect ed r esu lt s if ARG is less t han 10 char act ers. Ef fect comNVL plexand dat abases w itlit h er Orals. acle! Sycan st ems ab ase per th Av oid ively sit uatcreat ion selikan e dt hman is byage u sing not using You alwand ay s dat check t heex lengt Kevin es PL/ SQL, acle's of a st Ow r ingens w itex h tplor he LENGTH f unOr ct ion . answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 11.13.2 adv ant ag eINSTR of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y INSTR(str1, str2, [start_pos [,occurrence]]) Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Str1Dat a t y pes varchar2 stre ring b eing searched. and compSTR1 osit e is st rt hu ect u Str2 varchar2 We ar e look ing for an occur rence of t h is st rin g w it h in STR1 . Er r or han dling and except ions start_pos integer St ar t look ing at t his char act er posit ion . I nt er - pr ocess com mu nicat ions occurrance integer Look for t h e fir st , second , or n t h occur r ence. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch returns integer Ret ur ns t he char act er posit ion or 0. m or e Pr ogrI NSTR The am m ing fu nct Oracle ion r et Trur igger ns as and nu m St ber, or ed whPr ich oced is tur h eeschar , Thact ir derEdpitosit ionion , is of ant he inv nt aluable h occurrr esou ence rceof STR2 it hin STR1. for datwabase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. Zero is r et u r ned if no subst r ing or t h e requ est ed occu rr ence of t hat st r in g can not b e fou nd. [ Team To ex perLiB im ent ] w it h a comm a- d elim it ed st r ing, har d cod e a st r ing using DUAL. Th is SQL r et ur ns t h e fir st occur rence of a com m a.

[ Team LiB ] SQL> SELECT instr('aaa,bbb,ccc,ddd',',') FROM dual; INSTR('AAA,BBB,CCC,DDD',',') ---------------------------4

The second occur r ence of a com m a, st ar t in g fr om char act er posit ion 3 , is t he 8t h char act er .

SQL> select instr('aaa,bbb,ccc,ddd',',',3,2) from dual; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

INSTR('AAA,BBB,CCC,DDD',',',3,2) By Kevin Owens -------------------------------8 Pub lish er: Prent ice Hall PTR

The Pub t hirDat d e: occur r en of2 a Decem berce0 5, 003comm a, st ar t ing f rom ch ar act er p osit ion 2, is t he 12 t h ch ar act er . I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

SQL> select instr('aaa,bbb,ccc,ddd',',',2,3) from dual; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d INSTR('AAA,BBB,CCC,DDD',',',2,3) t-------------------------------eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. 12 Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases ules fw hich e easy t o manis age and odif y asfor t hecode t hat En cap su lat teo I incor NSTRpor intat o ea bu f unsiness ct ion . r The unct ionarNEXT_TOKEN a bu ild m in g block bu sin ess evolv es. Topics cov er ed include: par ses delim it ed st r ing s. This f unct ion ret u rn s TRUE if t h e subst r ing is fou nd. An OUT mod e par am et er , FOUND_AT_ POSI TI ON, ident ifies t h e locat ion of t he su bst r in g. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res CREATE OR REPLACE FUNCTION next_token (base_string INe VARCHAR2, Dat a t y pes and comp osit st r u ct u re looking_for IN VARCHAR2, start_looking_at IN ions INTEGER, Er r or han dling and except found_at_position OUT INTEGER) RETURN BOOLEAN IS I nt er - pr ocess com mu nicat ions result integer; BEGINDeclar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e found_at_position := INSTR (base_string,looking_for, Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce start_looking_at,1); for dat abase d ev elopers, d esign er s, and0); pr oj ect leader s look in g t o b uild an d m aint ain t r uly RETURN (found_at_position int ellig en t , com plex dat abases. END next_token; [ Team LiB ] Each call t o NEXT_TOKEN r et u rn s t he FOUND_ AT_ POSI TI ON. Hence r ep eat ed calls, each passing FOUND_ AT_POSI TI ON, w ill r et ur n all occur r ences of t he t ok en. For exam p le, p ass a com ma- d elim it ed st r ing and display each FOUND_AT_ POSI TI ON. The f ollow in g is a seq uence

of calls tLiB o NEXT_ TOKEN. Each sub sequ en t call begin s t he sear ch w it h FOUND_ AT_POSI TI ON [ Team ] + 1.

DECLARE str VARCHAR2(100) := 'aaa,bbb,ccc,ddd,eee,fff'; delimeter VARCHAR2(1) := ','; b BOOLEAN; found_at INTEGER; start_point INTEGER := 1; BEGIN b := next_token(str,delimeter,start_point,found_at); dbms_output.put_line(found_at); •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

start_point := found_at + 1;

By Kevin b Owens := next_token(str,delimeter,start_point,found_at);

dbms_output.put_line(found_at); Pub lish er: Prent ice Hall start_point :=PTR found_at

+ 1;

Pub b Dat :=e:next_token(str,delimeter,start_point,found_at); Decem ber 0 5, 2 003

dbms_output.put_line(found_at); I SBN: 0- 13 -0 850 33 -0 END;

Pages: 44 8

The r esult of t h is PL/ SQL b lock is t he locat ion of t h e fir st t h ree com m as. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 4 adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our 8 dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he 12 bu sin ess evolv es. Topics cov er ed include: Rat h er t han code a repeat ed sequ en ce, u se a WHI LE LOOP t h at p arses t he en t ire st r ing . The View in g const r aint s in t h e dat a dict ion ar y loop con t inues t o cy cle pr ov id ed t h e r et u r n code is TRUE. Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re DECLARE str VARCHAR2(100) Er r or han dling and except ions:= 'aaa,bbb,ccc,ddd,eee,fff'; delimeter VARCHAR2(1) := ','; b I nt er - pr ocessBOOLEAN; com mu nicat ions found_at INTEGER; Declar at iv e const r aint s, p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch start_point INTEGER :=including 1; BEGINm or e WHILE Pr ogr am m(next_token(str,delimeter,start_point,found_at)) ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly LOOP int ellig en tdbms_output.put_line(found_at); , com plex dat abases. start_point := found_at + 1; [ Team ] ENDLiB LOOP; END;

The W HILiB LE ]LOOP pr oduces all com m a occu r rences: 4, 8, 1 2, 16 , and 20 . Usin g t h is dat a w e [ Team can select all fields b et w een t he com mas. Th e fir st f ield is in ch aract er posit ions 1 –3, t he second in posit ions 5 –7. Th ese ar e st ar t an d st op p oin t s of t he st r ing . We can use SUBSTR t o get t hese field s, but SUBSTR r equir es a st ar t ing point and a leng t h. We can w r it e an enhan cem ent t o SUBSTR. This w ill b e a n ew fun ct ion t h at u ses st ar t an d st op poin t s. This fu nct ion is w rit t en as SUB_STRI NG.

CREATE OR REPLACE FUNCTION sub_string (base_string IN VARCHAR2, start_point IN INTEGER, end_point IN INTEGER) RETURN VARCHAR2 IS BEGIN • of Content s RETURN Table SUBSTR( Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on base_string, By Kevin Owens start_point, end_point-start_point+1); END sub_string; Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

Ther e ar e cur rent ly 33 t w-0o st r in g fun ct ion s: NEXT_TOKEN an d SUB_STRI NG. These fun ct ion s ar e I SBN: 0- 13 -0 850 likely candid at es for a st rin g m anip ulat ion packag e, called STRI NGS_PKG. Th e pack age Pages: 44 8 specif icat ion is show n her e.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tCREATE eaches you w hat y ou PACKAGE n eed t o kn ow t o build rob OR REPLACE strings_pkg ISust an d com plex dat ab ases f or y our b usiness. FUNCTION next_token Using(base_string easy- t o- follow inst r uctIN ionsVARCHAR2, an d ex am ples, t his book pr esent s t echniq ues t o t ake adv antlooking_for ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our IN VARCHAR2, dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he start_looking_at IN INTEGER, bu sin ess evolv es. Topics cov er ed include: found_at_position OUT INTEGER) RETURN BOOLEAN; FUNCTION sub_string View(base_string in g const r aint s in t h e IN dat a VARCHAR2, dict ion ar y start_point IN INTEGER, end_point Com plex r ule enf orcem en tIN INTEGER) RETURN VARCHAR2; END strings_pkg; PL/ SQL p r ogr am un it s and langu age f eat u res Ther eDat is no t o show e pack a t yneed pes and compt hosit e st rage u ct ubod re y. That will consist on ly of t he p rocedur e code f or NEXT_ TOKEN an d SUB_STRI NG, pr eviously show n. When t he f inal app licat ion code is w r it t en r orsthan and except ions using Er t he r ingdling s pack age, it h as t he f ollowin g f or m. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e DECLARE Pr ogr am m ing Oracle Tr igger s and := St or'aaa,bbb,ccc,ddd,eee,fff'; ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce str VARCHAR2(100) for dat abase d ev elopers, d esign er s, and delimeter VARCHAR2(1) := ',';pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. b BOOLEAN; found_at INTEGER; [ Team LiB ] start_point INTEGER := 1; BEGIN WHILE (strings_pkg.next_token

[ Team LiB ](str,delimeter,start_point,found_at)) LOOP dbms_output.put_line (strings_pkg.sub_string (str,start_point,found_at-1)); start_point := found_at + 1; END LOOP; dbms_output.put_line(substr(str,start_point)); END;

The ou t pu t f rom t his app licat ion piece now id en t if ies each t ok en in t he st r ing.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

aaa By Kevin Owens bbb . . . fffPub lish er: Prent ice

Hall PTR

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages:LPAD, 44 8 11.13.3 RPAD

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tLPAD(str1, eaches you wnew_length hat y ou n eed[,str2]) t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. RPAD(str1, new_length [,str2]) Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv varchar2 es. Topics cov er ed include: str1 The st r ing t o be pad ded. new_length integer The n ew len gt h of t he st r ing . Pad t he st r ing t o m ak e it t his long. View in g const r aint s in t h e dat a dict ion ar y str2 integer The p ad—ap pend t his t o STR1. I f n o STR2 is p assed, a BLANK Com plex r ule enf orcem enact t er is used f or padd ing. char returns p added r in fgeat t hat may b e pad ded w it h STR2 , or act ually PL/ SQL p varchar2 r ogr am un itThe s and langu st age u res t r un cat ed—t his depend s on t he lengt h of STR1 an d n ew _ leng t h. Dat a t y pes and comp osit e st r u ct u re The PAD f unct ion can b e used t o pad char act er s such as a blank or a zero. The pad can be a Er r or and ions st r in g—n ot han j ustdling a ch ar actexcept er . See comp lem ent ar y f unct ions t hat t rim : LTRI M, RTRI M. I nt er in - prg ocess nicat The f ollow t able com contmu ains f iveions SQL st at em ent s. Th e fir st t h ree st at em en t s lef t - pad a t hr eechar act er st r ing . The r esult is a six - char act er st ring . The four t h exam p le does no paddin g Declar e const r aint including rim y k last ey , uSQL nique, ey,ncat ch eck and m uch because t heatstivr ing is alr eads, y six ch aractper s. ar The st atf or emeign en t kt ru es t,he m or e st r in g—STR1 ex ceeds NEW _LENGTH, w hich is 6, and is t r un cat ed . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] The SQL st at e m e nt

Re t ur ns

SQL> SELECT LPAD('abc',6,'0') FROM dual;

000abc

SQL> SELECT LPAD('abc',6,'01') FROM dual;

010abc

SQL> SELECT LPAD('abc',6,'01234') FROM dual;

012abc

SQL> SELECT LPAD('abcdef',6,'01234') FROM dual;

abcdef

SQL> SELECT LPAD('abcdefg',6,'01234') FROM dual;

abcdef

The LPAD fun ct ion t r un cat es a st rin g w h en NEW_ LENGTH exceed s t he leng t h of t he st r ing. A st r in g fun ct ion can be bu ilt w it h som e d ef ensiv e code t hat t akes t h is int o consider at ion. Th e follow ing code r eplaces NEW_LENGTH w it h t he gr eat er of LENGTH( STR1 ) an d NEW_ LENGTH—t his pr event s st rin g t r u ncat ion. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

CREATE OR REPLACE FUNCTION left_pad Pub lish er: Prent ice Hall PTR (base_string IN VARCHAR2, Pub Dat e: Decem ber 0 5, 2 003 new_length IN INTEGER, I SBN: 0- 13 -0 850 33 -0 pad_string IN VARCHAR2) RETURN VARCHAR2 Pages: 44 8 IS BEGIN RETURN LPAD (base_string, Ef fect ively GREATEST(LENGTH(base_string), creat e an d man age com plex dat abases new_length), w it h Or acle! Sy st ems and dat ab ase ex per t pad_string); Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches END left_pad; you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Orfuacle featwur such oced ur es- f eat u r es t hat allow y our The LEFT_PAD nct ion illes n ot t r unas catt rig e tgers he st and r ing st inored t his pr call: dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y dbms_output.put_line(left_pad('abcdefg',6,'01234')); Com plex r ule enf orcem en t SQL p r ogr amdisplay un it s sand f eat u res This DPL/ BMS_OUTPUT t helangu or iginage al sev enchar act er st r ing —no t ru ncat ion. Dat adigit t y pes ositmeatstt ring. u ct uThe re b uilt - in st r ing fu nct ions can be com bined t o Num eric s ofand t en ncomp eed for const r uct f unct ions t hat pr ovid e sp ecific t yp es of p addin g. Th e follow ing fun ct ion u ses Er r or han dling and except ions DECODE, I NSTR, and concat enat ion t o r et ur n a n um ber as a st rin g, bu t w it h t w o d ecim al places filled . I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce CREATE OR REPLACE FUNCTION pad_number(N RETURN for dat abase d ev elopers, d esign er s, and pr oj ect NUMBER) leader s look in g t o VARCHAR2 b uild an d m aint ain t r uly IS int ellig en t , com plex dat abases. the_pad VARCHAR2(3); the_number VARCHAR2(30) := TO_CHAR(N); [ Team LiB ] BEGIN SELECT DECODE(INSTR(the_number,'.',1), 0, '.00', LENGTH(the_number)-1, '0',

NULL) INTO the_pad FROM dual; [ Team LiBLENGTH(the_number)-2, ] RETURN '$'||TO_CHAR(N)||the_pad; END;

The PAD _NUMBER fu nct ion r et ur ns t he st r ing $99 .0 0 wh en t h e inpu t is 9 9 an d ret ur ns $99 .3 0 w hen 99. 3 is passed . Built - in fu nct ions can be nest ed. Pad ding can b e accom plished on b ot h sid es of a st rin g b y nest ing LPAD and RPAD. Take a st r in g and lef t p ad 6 char act ers wit h a dash, t h en r ight pad t hat r esu lt a f ull 1 2 ch aract er s w it h an ast er isk .

•SQL> SELECT Table of Content s RPAD(LPAD('aaa',6,'-'),12,'*') FROM dual; Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

RPAD(LPAD('A By Kevin Owens --------------aaa****** Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN:LTRIM, 0- 13 -0 850 33 -0 11.13.4 RTRIM Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d LTRIM(str1, [,str2]) t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. RTRIM(str1, [,str2]) Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases tvarchar2 o incor por at e bu ules w hich str1 The st rsiness ing t o rbe t r im medar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: str2 integer This is on e or m or e char act er s. TRI M look s f or r epeat ed occur rences of t his st r ing and r emov es t hem . The default is blank . View in g const r aint s in t h e dat a dict ion ar y returns varchar2 The t rim m ed st r ing. I f t h e t r imm ing causes all char act er s t o be r im med, Com plex r ule enftorcem en t t he r et ur n is NULL. PL/M SQL p rion ogr am langu ageoccu f eatrruences res of a st r ing t hat m ake u p t he head or t ail The TRI f unct r emun ov itess and all r ep eat ed of t he st r ing . To t rim all blank s on eit h er side of a st r ing: Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions LTRIM(RTRIM(string)); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e The Ming funOracle ct ion r emov ess tand he firStstorsix eres s: , Th ir d Ed it ion , is an inv aluable r esou rce Pr ogrLTRI am m Tr igger ed ch Pr aract oced ur for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] 010101---01---01

On ce t heLiB LTRI [ Team ] M det ect s an en d t o t h e pat t er n, at t he fir st dash, no ot her ch ar act er s ar e r em ov ed.

The SQL st at e m e nt

Re t ur ns

SELECT LTRIM('010101--001--001','01') FROM dual;

--001--001

SQL> SELECT LTRIM('abbba','b') FROM dual;

abbba NULL

SQL> SELECT LTRIM(LTRIM(RTRIM('abbba','a'),'a'),'b') FROM dual;

Table of Content s 11.13.5 REPLACE •

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2[,str3]) 003 REPLACE(str1, str2 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

str1

varchar2 The st r ing t o be m odif ied.

str2 integer All occur ran ces of STR2 ar e r eplaced w it h STR3. The st r in g STR2 is Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t assu m ed t o ex ist at least once in STR1. Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t str3 eaches youvarchar2 w hat y ou This n eedist ot he knsubst ow t oitbuild ust an com dat ab f or tyhour b usiness. ut ion rob st r ing. I t dcan b eplex lar ger or ases sm aller an STR2. If STR3 is not pr ov ided, t h en all occur r en ces of STR2 ar e r eplaced w it h Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake NULL. adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our returns This could ber ules t he or replacement dat ab ases tvarchar2 o incor por at e bu siness wiginal hich arster ing easyif tno o man age and moccur odif yred, as tahem odif ied st r in g, er oredpossib ly NULL d ep en ding on t he sub st it u t ion. bu sin ess evolv es. Topics cov include: When w r it in g cod e t hat uses REPLACE, also look at t h e TRANSLATE fu nct ions. They each g const ainters subst in t h eit dat a dict ionREPLACE ar y per forView m stin r ing/ charract ut ion . The fun ct ion look s for ex act occur r en ces of STR2 . Each ex act occur r en ce is replaced w it h STR2 . Com plex r ule enf orcem en t The f ollow in g r eplaces t he st r ing ABC wit h XYZ. A let t er A, B, or C by it self is unchan ged. PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions SQL> SELECT REPLACE ('a b c ab bc abc','abc','xyz') FROM dual; I nt er - pr ocess com mu nicat ions REPLACE('ABCABB Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch --------------m or e a b c ab bc xyz Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Theellig TRANSLATE perfdat or mabases. s a char act er m apping —a d if fer ent t yp e of su bst it ut ion. The f ollow ing int en t , com plex r ep laces each let t er A wit h X, each B w it h Y, and each C w it h Z. [ Team LiB ]

SQL> [ TeamSELECT LiB ] TRANSLATE('a b c ab bc','abc','xyz') FROM dual; TRANSLATE(' ----------x y z xy yz

REPLACE can be used t o scru b d at a. To rem ov e all occu rr ences of a com m a follow ed by a line feed:

REPLACE(str, ','||CHR(10)) •

Table of Content s

Pr ogr am mping Or a clres e ® Tr i ggerusing s and Stor d P roce durefus,nct Thir d Edi ti onide PL/ SQL r ocedu b uilt t h e eREPLACE ion p rov

p ow er f ul d at a scru bbing t echniqu es. Su ppose w e w ant t o replace all occur rences of r ep eat ed st r ing w it h a sin gle By Kevin Owens occu r rence. The f ollowin g p r ocedu re t akes a base st rin g, an d a subst r ing of w hich r epeat ed occu r rences m ust b e r ep laced wit h a sin gle occu rr ence. The r esult is an I N OUT mod e par am et er hat ice is tHall he PTR scru bbed st r in g. Pub lish er: tPrent Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

CREATE OR REPLACE PROCEDURE remove_substring (base_string IN VARCHAR2, Ef fect ively creat e an d IN manVARCHAR2, age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t the_unwanted Kevin scrubbed_string Ow ens ex plor es PL/IN SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d OUT VARCHAR2) tIS eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. duplicate VARCHAR2(30) := the_unwanted||the_unwanted; Using BEGIN easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat:= ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our scrubbed_string base_string; dat abWHILE ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:duplicate, the_unwanted) (REPLACE(scrubbed_string, scrubbed_string) LOOP View in g const r aint s in t h e dat a dict ion ar y scrubbed_string := duplicate, the_unwanted); Com plex REPLACE(scrubbed_string, r ule enf orcem en t END LOOP; END remove_substring; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re This f unct ion can b e called consecut iv ely each t im e r ep lacing t he BASE_STRI NG w it h t he r esultErinr or SCRUBBED_STRI NG. This han dling and except ionsPL/ SQL block uses REMOVE_SUBSTRI NG t o f ir st replace r ep eat ed occu r rences of 01 w it h a single occur r en ce, t h en t h e same f or XY. I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce DECLARE for dat abase d ev elopers, d esign er s, := and'01010101-XY-XYXYXYXY'; pr oj ect leader s look in g t o b uild an d m aint ain t r uly base_string VARCHAR2(60) int ellig en t , com plex dat abases. clean_this_1 VARCHAR2(2) := '01'; clean_this_2 VARCHAR2(2) := 'XY'; [ scrubbed_string Team LiB ] VARCHAR2(60); BEGIN remove_substring(base_string, clean_this_1, scrubbed_string);

remove_substring(scrubbed_string, [ Team LiB ] clean_this_2, scrubbed_string); dbms_output.put_line(scrubbed_string); END;

The f inal st r ing is: 01-XY-XY

11.13.6 TRANSLATE

•TRANSLATE(str1, Table of str2, Content sstr3) Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

str1

varchar2 The st r ing t o be m odif ied.

Pub lish er: Prent ice Hall PTR

str2

integer

The f ir st char act er of STR2 is r eplaced w it h t he fir st char act er of STR3.

Pub Dat e: Decem ber 0 5, 2 003

str3

This I SBN:varchar2 0- 13 -0 850 33 -0 Pages: 44 8

is t he subst it ut ion st r ing. I t can b e lar ger or sm aller t h an STR2. I f STR3 is not pr ov ided, t h en all occur r en ces of STR2 ar e r eplaced w it h NULL.

returns varchar2 This could be t he or iginal st r ing if no replacement occur red, a m odif ied st r in g or possib ly NULL d ep en ding on t he sub st it ut ion. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor esion PL/m SQL, er ton o teh st e rSt , an d The TRANSLATE fu nct aps Or ch acle's aract eransw s fr om inrguct onurt oedanQuery ot her Langu st r ing.age Th is( SQL) is slig ht ly tdif eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. fer en t f rom REPLACE. To per for m t h e follow ing char act er m ap ping: Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: 1 -> overwrites each 2 -> overwrites each View in g const r aint s 3 -> overwrites each

-> A -> B in t h e dat a dict ion ar y -> C

Com plex r ule enf orcem en t TRANSLATE (string, 'ABC', '123'); PL/ SQL p r ogr am un it s and langu age f eat u res UsingDat TRANSLATE on comp a samp a t y pes and ositlee st strring u ct.u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions at ivTRANSLATE e const r aint('ABC s, including p rimCxy ar y kCBA','ABC','123') ey , u nique, f or eign k ey, ch eck , and m uch SQL> Declar SELECT Axy Bxy or e dual; 2 mFROM Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce TRANSLATE('ABCAXYBX for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly ------------------int ellig en t2xy , com3xy plex321 dat abases. 123 1xy [ Team LiB ] The f ollow in g ov er wr it es each d ig it w it h a zer o.

[ Team LiB ] TRANSLATE(str,'123456789','000000000');

The f ollow in g t ran slat es each d igit t o a zer o, an d t h en r emov es each zer o. This essent ially r em ov es all digit s.

REPLACE(TRANSLATE(str,'123456789','000000000'),'0');

The f ollow in g f un ct ion r et ur ns TRUE if t he st r ing cont ains an y digit s. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lishOR er: Prent ice Hall PTR CREATE REPLACE FUNCTION has_digits (str BOOLEAN Pub Dat e:VARCHAR2) Decem ber 0 5, 2RETURN 003 IS I SBN: 0- 13 -0 850 33 -0 one_to_nine CONSTANT VARCHAR2(9) := '123456789'; Pages: 44 8 zeroes CONSTANT VARCHAR2(9) := '000000000'; BEGIN -- convert all digits to a 0. -- INSTR returns number > 0 of string has a 0. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t RETURN INSTR(TRANSLATE(str,one_to_nine,zeroes),'0') > 0; Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d END has_digits; t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake [ Team LiB ] adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.14 Miscellaneous String Functions The f ollow in g list in clu des com m on st rin g f un ct ion s t hat ar e used in PL/ SQL.

ASCII

Ret ur ns t he d ecim al r ep resent at ion of a n um ber. The ar gu ment is a ch aract er . The f ollow in g SELECT r et ur ns 6 5. Th e fu nct ions ASCI I an d CHR p er f orm rev er se fu nct ions. SELECT ASCII('A') FROM dual; Ret ur of nsContent t he char Table s act er equiv alen t of a decim al n um ber. The ar gu ment is a The f ollow ing r et ur ns t he let t er A:

• CHR

. The isdure t hes,ASCI char act er. Pr ogr am m ing decimal Or a cl e ® Trnum i ggerber s and Storresult e d P roce Thir dI Edi ti on By Kevin Owens

SELECT CHR(65) FROM dual; Pub lish er: Prent Hall you PTR Supice pose

w ant t o inclu de t h e ASCI I char act er ( &) in a PL/ SQL p rog r am. This Plus. Realiz in g t hat ( &) is a SQL* Plus sp ecial char act er t hat 013 -0 850 denot es33 a -0comm and line ar gu m en t , y ou f ir st det erm ine t he decim al equiv alen t .

Pub Dat e: Decem ber t0o 5, SQL* 2 003 app lies I SBN:

Pages: 44 8

SQL> SELECT ASCII('&') FROM dual; 38 Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d Know ing t h e decim al equ ivalent , y ou can cod e t he f ollow ing . t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. string_1||CHR(38)||string_2 Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake CONCAT adv ant ag e of Or acle feat es such as t rigsgers stalent ored . pr oced ur es- f eat u r es t hat allow y our The f ollow in gurt wo exp ression ar e and eq uiv dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: var := string_1||string_2 var := concat(string_1, string_2) View in g const r aint s in t h e dat a dict ion ar y Com plex Ther ule f ir stenf fororcem m is ten het st and ard f orm for PL/ SQL code. The CONCAT f un ct ion is used in Pr o* C code b ecause t h e doub le pipe is com piled as a C oper at or. PL/ SQL p r ogr am un it s and langu age f eat u res GREATEST Ret ur ns t he lar gest v alue f rom a set of v alues. Ex pr essions can be n um bers, Dat a t ydat peses, and osit strrin u ct u re or comp char act ere st gs. Er r or han vardling := and GREATEST(var_1, except ions var_2, var_3, etc); LEAST Ret ur nscom t he mu smnicat allestions v alue f r om a set . I nt er - pr ocess var LEAST(var_1, var_2, var_3, Declar at iv e := const r aint s, including p rim ar y k ey , uetc); nique, f or eign k ey, ch eck , and m uch m or e LENGTH Ret ur ns t he lengt h of a st rin g. This fun ct ion w or ks w ell in conj unct ion w it h I NSTR, REPLACE, and TRANSLATE. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abaselen d ev elopers, d esign er s, and pr-oj ect s look := LENGTH('PL/SQL'); lenleader equals 6 in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ INITCAP Team LiB ]Ret ur ns a st r ing in in it ial cap s.

var := INITCAP('NEW YORK'); var equals 'New York' LOWER

Ret ur ns a low er case st r ing. The f ollow ing r et ur ns: n ew y ork . var := INITCAP('NEW YORK');

UPPER

Ret ur ns an u pper case st r in g. Th e follow ing r et u rn s: NEW YORK. var := INITCAP('new york');

[• Team LiB ] Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.15 Numeric Functions The f ollow in g in clu des com m on num er ic fu nct ions y ou can use in PL/ SQL p rog r ams.

Ret ur ns t he ab solut e valu e. The ar gum ent is any ex pr ession t hat ev aluat es t o a nu mb er .

ABS

var := ABS(var_1 - 100); Ret ur ns t he r em ain der follow ing div ision. The f ollow ing r et ur ns 3 .

MOD •

Table of Content s

MOD(11,4);

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

ROUND By Kevin OwensThe

Pub lish er: Pub Dat e:

ROUND f unct ion r ound s a n um ber or a dat e. You can specify t h e decim al place f or t he r oun ding . Use a second par am et er t o ind icat e t he degr ee of r ound ing. Posit iv e m ean s r ound t hat m any p laces t o t he r igh t . Negat iv e means Prent ice Hall r ound t h atPTR m any places t o t he left of t he decim al p oin t . Th e follow ing inclu des som eber rou ndin Decem 0 5, 2 003g ex am ples.

I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

ROUND(199.11); -- rounds to 200 ROUND(199.11, 1); -- rounds to 199.1 ROUND(199.125, 2); -- rounds to 199.13 ROUND(249.11, -2); -- rounds to 200 Ef fect ively creat e an d man age com plex-datrounds abases to w it h300 Or acle! Sy st ems and dat ab ase ex per t ROUND(250.11, -2); Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. SIGN Ret ur ns –1, 0, or + 1 based on t he sign of t he ex pr ession. Th e follow ing r et u rn s a Using easy- t–1 o- .follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t oSIGN(2-5+4*20-100) incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SQRT Ret ur ns t he squ are root of a n um ber . The f ollow in g r et ur ns: 1. 414 213 6. SQRT(2) View in g const r aint s in t h e dat a dict ion ar y TRUNC Tr uncat es a num ber or a dat e. You can sp ecify t he d ecim al posit ion for Com plex r ule enf orcem en t t r un cat ion . Similar t o r ound in g, y ou hav e an opt ional par am et er t h at is n eg at ive or p osit iv e. The f ollow ing ar e exam p les. PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re TRUNC(199.99); -- returns 199 TRUNC(199.99,1); Er r or han dling and except ions -- returns 199.9 TRUNC(199.125,2); -- returns 199.12 TRUNC(249.11,-2); -returns 200 I nt er - pr ocess com mu nicat ions TRUNC(299.11,-2); -- returns 200 Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ CEIL Team LiB ]Ret ur ns t he sm allest in t eg er gr eat er t han or equal t o t h e ar gum ent , w h ich is a nu mb er . A comm on nu mer ic calcu lat ion is t o r ound up non w hole nu mb er s. To r ound u p a num b er w it h a fr act ion, y ou add ( 0. 5) and t r uncat e t he nu mb er . CEI L does t h is for y ou.

CEIL(3.0); CEIL(3.1); CEIL(3.6); CEIL(-3.0); CEIL(-3.1); FLOOR



------

returns returns returns returns returns

3 4 4 -3 -3

Ret ur ns t he lar gest int eger less t han or equ al t o t he ar gu ment , w hich is a nu mb er . Table of Content s

Pr ogr am m ing FLOOR(-3.1); Or a cl e ® Tr i gger s and -Storreturns e d P roce dure -4s, Thir d Edi ti on By Kevin OwensFLOOR(-3.0);

FLOOR(3.1); FLOOR(3.6);

-- returns -3 -- returns 3 -- returns 3

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

POWER

Ret ur ns a nu m ber, raised t o t his pow er .

I SBN: 0- 13 -0 850 33 -0 Pages: 44 8 POWER(2,10)

= 1024

LOG(A,X) Com m on logar it hm . This an sw er s t he q uest ion : A valu e " A, " r aised t o t he p ower of w hat is eq ual t o " X" ? The LOG f un ct ion s r et u rn s t he wh at . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ensIFexA**B=X plor es PL/ SQL,LOG(A,X)=B Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d then t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. POWER(2,10) returns 1024 Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake POWER(4,3) returns 64 adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he LOG(2,1024) returns 10 bu sin ess evolv es. Topics cov er ed include: LOG(4,64) returns 3 View in g r aint t hion e dat EXP(X) Exconst pon en t ial sfuinnct of aX.dict ion ar y Com plex ulealenf t X. LN(X) Natr ur logorcem arit h menof PL/ SQL p r ogr am un it s and langu age f eat u res EXP(1) = 2.71828183 Dat a t yLN(2.71828183) pes and comp osit = e st 1r u ct u re Er r or han dling and except ions COS(X) Cosine of X. I nt er - pr ocess com mu nicat ions COSH(X) Ar ccosine of X. Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch SIN(X) Sine of X. m or e SINH(X) Ar csine of X. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce TAN(X) en t of X. d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly for dat abaseTang d ev elopers, int ellig en t , com plex dat abases. TANH(X) Ar ct angent of X. [ Team LiB ] An ex am ple of a Pyt h agor ean r elat ion is: For an y nu mb er X: POWER(SIN(X),2) + POWER(COS(X),2) = 1

[[ Team Team LiB LiB ]]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.16 Random Number Generation You use t he DBMS_RAND OM packag e t o g en er at e r an dom nu m bers. You set t h e seed wit h t h e SEED f unct ion, w hich is ov erload ed .

PROCEDURE seed(val IN BINARY_INTEGER); PROCEDURE seed(val IN VARCHAR2); •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Tw o m et hod s for set t ing a seed ar e: By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 dbms_random.seed(123456); Pages: 44 8 dbms_random.seed(TO_CHAR(SYSDATE,'dd-mon-yyyy hh24:mi:ss');

The f un ct ion VALUE gener at es a 38 - digit pr ecision n um ber w it hin t he r ang e: Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 0.0

Teamselect LiB ] TRUNC(SYSDATE) from dual; TRUNC(SYSDATE) -------------------06-may-2004 00:00:00

To see if a d at e v ariab le pr ecedes t he cu rr ent dat e, com par e it t o t he t ru ncat ion of t he cur r en t day .

IF date_variable < TRUNC(SYSDATE) THEN •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

11.17.2 TO_CHAR, TO_DATE By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages:TO_CHAR(D 44 8 FUNCTION DATE [,format_model VARCHAR]) RETURN VARCHAR2;

This f unct ion is ov er loaded t o conv er t NUMBER, I NTEGER, and ot her t y pes t o char act er st in gs. This show s how t o age use com t he plex fun ctdat ion abases t o convweritthaOr dat e t oSy a st stems rin g.and You dat canabsup an t Efrfect ively creat e an d man acle! aseply ex per opt ion Ow al for m at st r ing it hSQL, t he fOr unct ion. answ A f ewer for sh own Langu h er e. age ( SQL) , an d Kevin ens ex plor es w PL/ acle's t om t hat e st Strrings uct urare ed Query t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow instFor r uctmions an d ex s t echniq t oCH t ake Sa m ple a t Mode l am ples, t his book pr esent Out put fr omues TO_ AR adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our TO_CHAR(SYSDATE,'Day') dat ab ases t o incor por at e bu siness r ules w hich ar e easy Wednesday t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: TO_CHAR(SYSDATE,'Mon'); Aug TO_CHAR(SYSDATE,'YYYY'); View in g const r aint s in t h e dat a dict ion ar y TO_CHAR(SYSDATE,'Day Month YYYY'); Com plex r ule enf orcem en t TO_CHAR(SYSDATE,'DD-MON-YYYY');

2003

PL/ SQL p r ogr am un itMonth s and langu f eat u res TO_CHAR(SYSDATE,'Day DD, age YYYY');

Wednesday August 06, 2003

Wednesday August 2003 06-AUG-2003

Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions FUNCTION [,format_model VARCHAR]) RETURN DATE; I nt er -TO_DATE(V pr ocess comVARCHAR2 mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch This fm unct or eion conv er t s a st r in g t o a DATE t yp e. You can use a for m at m odel if t h e st rin g for m at is not con sist ent w it h t h e DATE for m at in t h e dat ab ase. Th e follow ing con ver t s a st r ing Pr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce t o ogr a DATE. for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] DECLARE D DATE;

str LiB VARCHAR2(30) := 'Wednesday August 06 2003'; [ Team ] fmt VARCHAR2(30) := 'Day Month DD YYYY'; BEGIN D := TO_DATE(str, fmt); END;

11.17.3 ADD_MONTHS

FUNCTION ADD_MONTHS(in_date DATE, months NUMBER) RETURN DATE; •

Table of Content s

Pr ogr am m ing a cl es® or Tr isubt gger sract andsStor Thir d Edi This f unct ionOradd on ee dorP roce m ordure e ms,ont hs t o tiaondat e

ar gu ment .

By Kevin Owens

I f t oday is t h e last day of t he m ont h , such as Oct ober 31 , and t h e follow ing m ont h has f ew er day s, Nov em ber , t h is fun ct ion r et ur ns Nov emb er 30. The f ollow ing declares D ATE v ar iables andPub init ializes t hem t oPTR dat es: adv anced by one mon t h and one m ont h in t he p ast . lish er: Prent ice Hall Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

same_day_next_month DATE := ADD_MONTHS(SYSDATE, 1); same_day_last_month DATE := ADD_MONTHS(SYSDATE, -1); Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness.

11.17.4 LAST_DAY

Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: FUNCTION LAST_DAY(in_date DATE) RETURN DATE; View in g const r aint s in t h e dat a dict ion ar y plexr et r ule enft horcem t of t h e cur rent m ont h r elat iv e t o I N_ DATE. The f ollow ing This fCom unct ion ur ns e lasten day r et ur ns t h e last day of t h e cur r en t m ont h . PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions v_date :=- prLAST_DAY(SYSDATE); I nt er ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch Selectmall or epr ofessor s w ho hav e been hir ed any t im e in t he cu rr ent m ont h. I f t h e cur r en t day is July 2 0, w e w an t all r ow s w her e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] hire_date >= July 1 at time 00:00:00

Sub t ract [ Team LiB ] a m ont h f r om t he cur r ent day w it h ADD_MONTHS. Get t he last d ay of t hat m ont h w it h LAST_DAY. Add a day , w hich y ield s t he fir st day of t he cur r en t m ont h . TRUNC gives t im e 0 0: 00 : 00 on t he f ir st of t he cur r en t m ont h. The b eg inning of t im e f or t he cur r ent mon t h is:

SELECT TRUNC(LAST_DAY(ADD_MONTHS(SYSDATE, -1))+1) FROM dual; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

All pr of essor s hir ed t h is mon t h are: By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 0- 13 -0 850 33 -0 SELECTI SBN: prof_name, hire_date FROM Pages: professors 44 8 WHERE hire_date >= TRUNC(LAST_DAY(ADD_MONTHS(sysdate, -1))+1);

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Let ' s comp ut eex t hplor e last daySQL, of t he ev iouansw s m ont Kevin Ow ens es PL/ Orpr acle's er th. o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he v_date LAST_DAY(ADD_MONTHS(SYSDATE, -1)); bu sin ess:= evolv es. Topics cov er ed include: The v View alue in f org const V_D ATE wsillinintclud e hou rs, ion m inu r aint h e dat a dict ar yt es, an d seconds, f or exam ple: Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res 30-JUN-2003 Dat a t y pes 14:32:00 and comp osit e st r u ct u re Er r or han dling and except ions I f w e add a d at e and t r un cat e, t he r esult is 1- JULY- 2 003 0 0: 00 : 00. We can t hen select all com mu hnicat eventIsntinert-hpr e ocess cur rent m ont w it ions h t he q ualifier: Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly WHERE some_date_column >= TRUNC(v_date+1) int ellig en t , com plex dat abases. [We Team can LiB filt er] all ev en t s pr evious t o t h e cur rent m ont h w it h

[ Team LiB ] WHERE some_date_column < TRUNC(v_date+1)

The b eg inning of t h e cur rent m ont h is alw ays:

TRUNC(LAST_DAY(ADD_MONTHS(sysdate, -1))+1)

11.17.5 MONTHS_BETWEEN •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

FUNCTION MONTHS_BETWEEN (date1 DATE, date2 DATE) RETURN NUMBER; Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

This f unct ion0- 13 r et-0ur ns33t-0 h e num ber of m ont hs bet w een t w o dat es. A f r act ion al par t is in clu ded I SBN: 850 in t he Pages: r et ur ned num ber . The follow ing ret u rn s t he n um ber of m ont h s bet w een Janu ary 1 an d 44 8 July 1 . This b lock assigns N t he value of 6 . 0. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake DECLARE adv ant e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our D1 ag DATE; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he D2 DATE; bu sin ess evolv es. Topics cov er ed include: N NUMBER(4,2); BEGIN D1:= to_date('1-Jul-2004','DD-MON-YYYY'); View in g const r aint s in t h e dat a dict ion ar y D2:= to_date('1-Jan-2004','DD-MON-YYYY'); N Com := MONTHS_BETWEEN(D1, plex r ule enf orcem en t D2); -- N is 6 END; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e 11.17.6 NEW_TIME

st r u ct u re

Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e NEW_TIME (in_date DATE, time_zone VARCHAR2, FUNCTION time_zone_of_result VARCHAR2) RETURN DATE; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en tion , com plex dat This f unct evaluat es abases. I N_D ATE ( relat ive t o a t ime zone—TI ME_ZONE) an d ret ur ns a new t im e ( r elat iv e t o TI ME_ZONE_OF_RESULT) . [ Team LiB ] For exam ple, t ak e t h e cu r rent t im e zone, assum ing East ern St and ar d Tim e, and conv er t it t o Pacific St and ar d Tim e.

[ Team LiB ]

pst_date := NEW_TIME(SYSDATE, 'EST','PST');

Con ver t 1 2 n oon t oday , East er n St an dar d Tim e, t o GMT.

DECLARE today DATE:= sysdate; converted_time DATE; BEGIN • Table of Content s -- set converted_time to 12 noon today. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on converted_time := TRUNC(today) + 1/2; By Kevin Owens

-- convert this to GMT time. converted_time := NEW_TIME(converted_time, 'EDT','GMT'); Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 dbms_output.put_line(converted_time);

END;

I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

The f ollow in g t able list s t he st r ing abbr ev iat ion s for t ime con ver sion s. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t TimOre acle's Zon e answ er t o t h e St r uct ur ed Query Conve si on St ri ,ng Kevin Ow ens ex plor es PL/ SQL, Langu rage ( SQL) an d t At eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. lant ic St an dar d or Day light Time AST, ADT Using follow instlig r uct an d ex am ples, t his book pr esent s t echniq ues t o t ake Berin geasySt ant odar d or Day htions Time BST, BDT adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our Cent al St tandar d por or Day Timer ules w hich ar e easy t o man age and CST, CDT dat abrases o incor at e light bu siness m odif y as t he bu sin ess evolv es. Topics cov er ed include: East er n St an dar d or Day light Time EST, EDT Gr een w ich Mean Tim e View in g const r aint s in t h e dat a dict ion ar y Alaska- Haw aii St an dar d Tim e or Dayligh t Tim e Com plex r ule enf orcem en t Mou nt ain St andar d or Day light Tim e

GMT

p r ogr amard un itTim s and NewfPL/ ounSQL dland St and e langu age f eat u res

NST

Pacific DatStaand t y pes ar dand or Day comp lig osit ht Tim e ster u ct u re

PST, PDT

Yuk on ard or D ayligh t Tim e Er rSt orand han dling and except ions

YST, YDT

HST, HDT MST, MDT

I nt er - pr ocess com mu nicat ions

11.17.7 NEXT_DAY

Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , NEXT_DAY(in_date com plex dat abases. DATE, weekday VARCHAR2) RETURN DATE; FUNCTION [ Team LiB ] This f unct ion can b e used, f or exam ple, t o r et u r n t h e DATE associat ed wit h nex t Monday . Th e par am et er I N_ DATE can be any dat e. W e can com put e t he f irst day of a mon t h w it h LAST_ MONTH an d LAST_DAY. I n cor por at ion of t his f un ct ion enables com put at ion of t he fir st

Mon day LiB of a] m on t h. Th e valu es f or WEEKDAY are [ Team 'MONDAY' 'TUESDAY' 'WEDNESDAY' 'THURSDAY' 'FRIDAY' 'SATURDAY' 'SUNDAY' •

Table of Content s

What day is t he f ollow ing Mon day ?

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

v_date := NEXT_DAY(SYSDATE, 'MONDAY'); Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Get t he f ir st Tuesd ay of last m ont h.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tDECLARE eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. start_of_last_month DATE; Usingfirst_tuesday easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake DATE; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our BEGIN dat abstart_of_last_month ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he := bu sin ess evolv TRUNC(LAST_DAY(ADD_MONTHS(SYSDATE, es. Topics cov er ed include: -2))+1); first_tuesday := View in g const r aint s in t h e dat a dict ion ar y NEXT_DAY(start_of_last_month, 'TUESDAY'); END; Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res

11.17.8 ROUND, TRUNC Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions DeclarTRUNC(in_date at iv e const r aint s,DATE) including p rimDATE; ar y k ey , u nique, f or eign k ey, ch eck , and m uch FUNCTION RETURN m or e ROUND(in_date DATE) RETURN DATE; FUNCTION Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for evtelopers, d esign s, and pr oj ect s look in g t o b uild an d m aint ain t r uly Timdat e ofabase day stdar s w it h hour s, mer inut es, secon ds leader at : int ellig en t , com plex dat abases. [ Team LiB ]

00:00:00

[ Team LiB ] I f you TRUNCATE dat e, t he r esu lt is t hat dat e at zer o h our s, min ut es, and second s. This is eff ect iv ely t h e st ar t of t h e day . The f ollow in g d eclar es a DATE v ar iab le and init ializes it t o t he st ar t of t h e cu r rent day .

start_of_day DATE := TRUNC(SYSDATE);

The st ar t of t om orr ow is:



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens start_of_tomorrow DATE := TRUNC(SYSDATE + 1);

I f a Pub DATE lish er:v ar Prent iabice le Hall is set PTR t o a t im e fr am e w it hin t he cur r ent day , t he f ollow in g is TRUE: Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

start_of_day = 30 THEN RAISE class_full; END IF; [ Team ] The u ser of y our packag e m ust w r it e code t o hand le t he ex cept ion , similar t o t he ZERO_DI VI DE except ion hand ler . St y le is a concern . Ther e ar e alw ays opt ions w it h r esolv in g t he u nexp ect ed con dit ion. You can r et ur n a st at us t o indicat e t h e r eason for t he u nexp ect ed con dit ion. Th e ch oice t o use an except ion has an im pact on t h e code using y our p ack age. I f y our p ack age f r eq uent ly r aises except ions, t h e code using y our p ack age will b e chopp y. You shou ld r aise an ex cep t ion only w hen t he ex cept ion condit ion is ext rem ely rar e. You can com bine ex cep t ions w it h st at us r et ur ns. For exam ple, y ou can r et ur n a st at us if t h e class is f ull, b ut r aise an ex cept ion if t he caller at t em pt s t o r egist er a st ud en t f or a n onexist ent class. From an applicat ions per spect iv e, t he f ollowin g p ack age illust r at es t h e use of an ex cep t ion. This p ack age adds n um ber s. The pack age r aises an ex cept ion if t he su m is zero. I n t h is •exam ple, a zer Table of con Content s ed an in valid result and t he p ack age t hr ow s t he ex cep t ion . o is sid er Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

CREATE OR REPLACE PACKAGE add_pkg IS Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

zero_amount EXCEPTION; Pages: 44 8

FUNCTION add(A NUMBER, B NUMBER) RETURN NUMBER; END add_pkg; Ef fect ively e an d PACKAGE man age com plex dat abases CREATE ORcreat REPLACE BODY add_pkg IS w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou nNUMBER, eed t o knBowNUMBER) t o build RETURN rob ust anNUMBER d com plex dat ab ases f or y our b usiness. FUNCTION add(A IS Using easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake result NUMBER; adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our BEGIN dat ab asesresult t o incor:= por A+B; at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics ed include: IF (result = cov 0) er THEN raise zero_amount; END IF; RETURN result; END add; View in g const r aint s in t h e dat a dict ion ar y END add_pkg; Com plex r ule enf orcem en t The uPL/ ser SQL of t he pack age a choice how w r it e t he code. Th e cod e can in clud e an p r ogr am unhitas s and languin age f eatt ou res except ion hand ler or not inclu de an except ion han dler . W hen an except ion is r aised, execut iona of t he im m ediat block Dat t y pes and compeosit e st rends. u ct u re" Block " m eans t h e imm ediat e BEGI N- END block or subp rog r am body . I f t h e imm ediat e b lock h as an ex cep t ion h andle, t h en cont r ol p asses t o t hat poin t . han I f t her e isand no ex cep t ion Er r or dling except ionsh andler , t he ex cep t ion p rop agat es back t o t he n ex t - m ost out er b lock or calling subp rog r am. I nt er - pr ocess com mu nicat ions The f ollow in g t able show s t w o pr ocedu res; on e hand les t he except ion, t he ot h er does not . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] Proced ure w i t h Ex cep t ion H an dl er PROCEDURE proc_1 IS N NUMBER; BEGIN N := add_pkg.add(1,2); dbms_output.put_line(N); EXCEPTION WHEN add_pkg.zero_amount THEN dbms_output.put_line(0); END;



Proced ure w i t hout Exce pt i on H a ndl in g PROCEDURE proc_1 IS N NUMBER; BEGIN N := add_pkg.add(1,2); dbms_output.put_line(N); END;

Table of Content s

Pr ogr am m ing 11.18.2 Blocks Or a cl e ® Trwith i gger s Exception and Stor e d P roceHandlers dure s, Thir d Edi ti on By Kevin Owens

Mod if y t he pr eceding pr ocedur e PROC_1 so t h at it loops. PROC_1 below calls ADD_PKG once per loop it erat ion . Theor et ically, any it erat ion can r aise an except ion. The behav ior of t h is code Pub islish t her: at Prent a sin icegle Hallexcept PTR ion t erm inat es p rocessing . The f ir st pass w ill add a min us one t o a one.Pub ThDat is e: w ill raise cep t ion. Th e resolut ion of t he ex cept ion is t o pr int using Decem ber t0he 5, 2ex 003 DBMS_I OUTPUT. SBN: 0- 13 -0 850 33 -0 Pages: 44 8

When ADD_ PKG r aises an ex cept ion , t he pr ocedu re it self, ADD, h as no ex cep t ion h andler . Ther ef or e, t he ex cept ion pr opag at es t o t he callin g p rocedur e, in t his case PROC_1. This pr oced ur e has an ex cept ion h andler; hence, cont r ol g oes t o t he hand ler , w hich pr int s a zer o. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easyo- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake CREATE OR tREPLACE PROCEDURE proc_1 adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our IS dat abNases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he NUMBER; bu sin ess evolv es. Topics cov er ed include: BEGIN FOR VAL IN -1..5 LOOP N := add_pkg.add(1,VAL); View in g const r aint s in t h e dat a dict ion ar y dbms_output.put_line(N); END LOOP; Com plex r ule enf orcem en t EXCEPTION WHEN add_pkg.zero_amount THEN PL/ SQL p r ogr am un it s and langu age f eat u res dbms_output.put_line(0); END; Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions The cod e in PROC_1 can alt er nat iv ely capt ur e each p ossible f ailed add it ion b y em bedd ing t he ADD_IPKG in ancom ex cept nt er -call pr ocess mu ion nicatblock ions . Th is is show n next . This design allow s ad dit ions t o cont inu e w hile capt ur ing t hose t h at f ail. The f ollow in g ex cept ion han dler exist s w it hin a Declar e const r aint s, ex including rim ars,y cont k ey ,r ol u nique, k ey, , and m uch BEGI NENDat b iv lock . Wh en t he cep t ion poccur j um psf or t o eign t he en d ofcht eck h e cur rent block . or eis wit h in t h e loop, h en ce it er at ion con t inues. The bm lock Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [CREATE Team LiB OR ]REPLACE PROCEDURE proc_1 IS N NUMBER; BEGIN

FORLiB VAL [ Team ] IN -1..5 LOOP BEGIN N := add_pkg.add(1,VAL); dbms_output.put_line(N); EXCEPTION WHEN add_pkg.zero_amount THEN NULL; END; END LOOP; END;

11.18.3 The EXCEPTION Clause The ex cep t ion clause can be at t he end of a pr ocedu re, f unct ion, or declare b lock . Pr eviou s exam ples of t h e pr oced ur e PROC_1 illu st r at e b ot h cases. •

Table of Content s

Pr ogrfam m ing Orex a clcep e ® Tr i gger and e d rPat roce Ediw tiillin on g The ollow in g t ion sysnt ax Stor illust es dure cod s, e tThir hatd is

t o han dle one of t wo except ions.

Any PL/Owens SQL code can ex ecu t e w it hin t he ex cept ion h andler. By Kevin

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0

EXCEPTION Pages: 44 8 WHEN exception_name THEN do_something; WHEN another_exception_name THEN do_something; END; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens plorler escan PL/ SQL, Or acle's answ er t o t hclause. e St r uctThis ur edprQuery An ex cept ion ex hand cont ain a WHEN OTHERS ogr amLangu log ic age hand( SQL) les an, yan d texcept eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ion t hat occu rs. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: EXCEPTION WHEN OTHERS THEN do_something; END; View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t A W HEN OTHERS can be com bined w it h ot her except ions. Use WHEN OTHERS t o cat ch PL/ SQL p r ogr am un it s and langu age f eat u res except ions not p r ev iously list ed in t he except ion han dler . Th e follow ing exam ple p rin t s a specifDat ic ma essage w hen t he osit ZERO_ t y pes and comp e st rAMOUNT u ct u re except ion is r aised. For an y " ot her " ex cept ion , a gener ic m essage is d isplay ed. Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch EXCEPTION m or e WHEN add_pkg.zero_amount THEN Pr ogr am mdbms_output.put_line('Got ing Oracle Tr igger s and St or ed zero_amount Pr oced ur es , Thexception'); ir d Ed it ion , is an inv aluable r esou rce WHEN OTHERS THEN d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly for dat abase d ev elopers, some other exception'); int ellig en tdbms_output.put_line('Got , com plex dat abases. END; [ Team LiB ] A p r ogr am can h ave mu lt ip le ex cept ion hand ler s. The n ex t pr ocedu r e illu st r at es t h is. Th e pr oced ur e, PROC_1, has t w o ex cep t ion h andler s. One ex cept ion h andler exist s w it hin t he

BEGI N- END [ Team LiB ] b lock . This capt ur es t he ZERO_AMOUNT ex cep t ion. Th e ot her ex cept ion han dler is at t he p rocedur e level an d will cap t ur e a VALUE_ERROR. A VALUE_ERROR is an Or acle p redef in ed ex cept ion r aised on con ver sion er ror s such as:

N NUMBER := TO_NUMBER('ABC');

This v ersion of PROC_1 illu st r at es ex cept ion han dling but is also an exam ple of chop py code.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

CREATE OR REPLACE PROCEDURE proc_1 By Kevin Owens IS N NUMBER; BEGIN Pub lish er: Prent ice Hall PTR FOR VAL IN -1..5 LOOP Pub Dat e: Decem ber 0 5, 2 003 BEGIN I SBN: 0- 13 -0 850 33 -0 N := add_pkg.add(1,VAL); Pages: 44 8 dbms_output.put_line(N); EXCEPTION WHEN add_pkg.zero_amount THEN NULL; END; Ef fectEND ivelyLOOP; creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d EXCEPTION t eaches youVALUE_ERROR w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. WHEN THEN dbms_output.put_line('Got value error'); Using END; easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sindoes ess evolv es. Topics covex ercep ed tinclude: Why PROC_1 hav e an ion handler f or VALUE_ERROR? Th e only r eason is t o illust rat e t he v ar ious placement s of ex cept ion hand ler s. Ther e is not h in g in t h is cod e t hat could possib ly raise such an ex cep t ion . That is, t her e ar e no PL/ SQL st at em en t s t hat can View in g const r aint s in t h e dat a dict ion ar y cause t he t yp e of er r or w e w ould see if w e ex ecu t ed t h is st at em ent : Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re N NUMBER := TO_NUMBER('ABC'); Er r or han dling and except ions Ex cepItnt ion andler t hat mu cannicat n evions er be in vok ed sh ould be r em ov ed f r om t he cod e. But h er e is a er -hpr ocesss com v er sion of PROC_ 1 t h at shou ld h ave a VALUE_ ERROR ex cep t ion h andler . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch What m if or w ee chang ed PROC_1 as f ollow s? I n t he follow in g, PROC_ 1 r eceiv es a VARCHAR2 st r in g t hat is con ver t ed t o a NUMBER w it hin t he loop . The TO_NUMBER conv er sion could pot entam ially r aise a VALUE_ ERROR exor cep Pr ogr m ing Oracle Tr igger s and St edt ion. Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] CREATE OR REPLACE PROCEDURE proc_1(END_POINT IN VARCHAR2) IS

N NUMBER; [ Team LiB ] BEGIN FOR VAL IN -1..TO_NUMBER(END_POINT) LOOP BEGIN N := add_pkg.add(1,VAL); dbms_output.put_line(N); EXCEPTION WHEN add_pkg.zero_amount THEN NULL; END; END LOOP; EXCEPTION WHEN VALUE_ERROR THEN dbms_output.put_line('Got value error'); END; •

Table of Content s

Hav in g sh own t h e v arious places w h er e ex cept ion han dlers can be declar ed, t h e ju st if icat ion Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on for each of t hese except ion hand ler s is q uest ion able. A bet t er PROC_1 pr ocedur e w ould def in e By Kevin t he parOwens amet er END _POI NT as a NATURAL su bt y pe. This const r ains t he par am et er t o zer o or gr eat er. I f t h is w er e d one, t he VALUE_ERROR except ion w ould not b e necessar y and could t hen be r em oved. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 11.18.4 SQLCODE and SQLERRM Pages: 44 8

SQLCODE and SQLERRM ar e b uilt - in f un ct ion s t hat only hav e m eaning w it hin an ex cep t ion han dler . They ev aluat e t o t h e cu rr ent except ion er r or nu m ber and err or m essag e. These fu nct ions ar e f requ en t ly used w it h DBMS_ OUTPUT as a d eb ugg in g mechanism . They ar e Ef fect ively e anOTHERS d man age w it hlerOr usually in acreat WHEN p artcom of plex an exdat cepabases t ion hand . acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d tAeaches you y ou ow ent t o sbuild an d tcom plex ab ases our yb usiness. p r ocedu re w hat it h m anyn eed D MLt ost kn at em can rob be dust iff icult o d eb ug.dat There can f or be yman r easons for failur e. A p rocedur e m ay f ail because of a d uplicat e insert . I t m ay f ail w it h a conv er sion Using t o-infollow uctoions an deric ex am ples, t his book pr esent s t echniq ues t o t ake err or weasyh en it ser t s tinst ex tr int a num f ield . adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases in t og incor e buur siness ules w hich t o man age and m odif as dler t he is The f ollow ex ampor pleatcapt es an r inv alid inserart .eAeasy WHEN OTHERS ex cept ion yhan bu sin ess tevolv es. cov er ed included hat pr intTopics s SQLCODE andinclude: SQLERRM. This b lock sim ulat es inser t in g char act er t ext int o a colum n w it h a NUMBER t yp e. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res DECLARE Dat a t y pes and comp osit e st r u ct u re N varchar2(30) := 'not a number'; BEGIN Er r or han dling and except ions UPDATE professors SET salary=TO_NUMBER(n); EXCEPTION I nt er - pr ocess com mu nicat ions WHEN OTHERS THEN dbms_output.put_line('SQLCODE:'||SQLCODE); Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m ordbms_output.put_line('SQLERRM:'||SQLERRM); e END; Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly Theellig ou en t put ,t com f romplex t hisdat block is: int abases. [ Team LiB ]

SQLCODE:-1722 [ Team LiB ] SQLERRM:ORA-01722: invalid number

An I NVALI D _NUMBER is an Or acle p redef in ed ex cept ion r aised if con ver sion f ails dur ing a SQL st at ement . For ex am ple:

UPDATE professors SET salary=TO_NUMBER('abc');

SQLCODE and SQLERRM ar e u su ally u sed in WHEN OTHERS hand ler s t o cat ch un ex pect ed except ions. I f y ou kn ow in adv ance t hat you w ill hav e t o cat ch an I NVALI D_NUMBER •except ion, you Table of code Content w ill t hse follow ing: Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR

EXCEPTION Pub Dat e: Decem ber 0 5, 2 003 WHEN INVALID_NUMBER THEN I SBN: 0- 13 -0 850 33 -0 dbms_output.put_line('Number conversion in SQL'); END; Pages: 44 8

Using % TYPE is a pr act ice t h at h elp s avoid r un- t im e- t y pe conv ersions. To imp lem ent t he Ef fect ively creat ePL/ anSQL d man age as com plex dat rabases w it hatOr Sy st ems and dat ab ase extper afor em en t ioned block a pr ocedu e t hat upd esacle! t he PROFESSORS t able, pass he t Kevin ens es PL/ SQL, acle's er t o t hy eofStan r uct ur ed Query Langu ex age ( SQL) , an salary Ow u sin g aex %plor TYPE. This elimOr inat es t hansw e possibilit I NVALI D_ NUMBER cep t ion an dd eaches ou t nion eedh andler t o kn ow t he needyou f or w anhat ex ycep . t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: CREATE OR REPLACE PROCEDURE update_salaries(new_sal professors.salary%TYPE) IS BEGINView in g const r aint s in t h e dat a dict ion ar y UPDATE professors SET salary=new_sal; Com plex r ule enf orcem en t END update_salaries; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a The t y pes RAISE and compStatement osit e st r u ct u re 11.18.5 Er r or han dling and except ions An ex cept ion con dit ion occur s w it h t he follow in g con dit ions: I nt er - pr ocess com mu nicat ions App licat e declares an except ion ar and t he, uPL/ SQL fcode r aises hateck ex, cep . This Declar ation iv e cod const r aint s, including p rim y k ey nique, or eign k ey, t ch andt ion m uch is t he case w it h t he AD D_PKG pack age code on p. 366 . I t r aises an ex cept ion w hen t he m or e r esult of t he op er at ion is zer o. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce Orabase acle raises an ex cep t ion.erTh occur s if insers tlook a duinplicat int oan a dprm imaint aryain keyt r uly for dat d ev elopers, d esign s,isand pr oj ecty ou leader g t o beuild colum n. An ot her exam ple is a div ide by zer o. int ellig en t , com plex dat abases. This sectLiB ion] cov er s t h e t opic of r er aising an except ion insid e an ex cep t ion handler . [ Team You can capt u r e an ex cep t ion, han dle it , an d t hen r aise it . Wh y? You may wan t t o w r it e except ion- h andling code f or t h e pr imar y p ur pose of capt ur ing t h e er r or r ecor din g it but w ant t o t hr ow it back t o t he pr oced ur e t hat called y ou. Th e pr oced ur e t hat called you m ay need t o

k[ now Teamsuch LiB an ] ex cep t ion occur r ed. Con sid er t he f ollow ing code, used ear lier . Th is pr oced ur e includes t h e except ion hand ler p lus RAI SE st at em ent in t he BEGI N- END b lock .

CREATE OR REPLACE PROCEDURE proc_1 IS N NUMBER; BEGIN FOR VAL IN -1..5 LOOP BEGIN N := add_pkg.add(1,VAL); dbms_output.put_line(N); EXCEPTION • Table of Content s WHEN add_pkg.zero_amount THEN Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on dbms_output.put_line('zero_amount'); By Kevin Owens RAISE; END; END LOOP; Pub lish er: Prent ice Hall PTR EXCEPTION Pub WHEN Dat e:VALUE_ERROR Decem ber 0 5, 2 003 THEN dbms_output.put_line('Got value error'); I SBN: 0- 13 -0 850 33 -0 END; Pages: 44 8 What is t h e ex ecu t ion pat h w hen AD D_PKG r aises t h e ZERO_ AMOUNT ex cept ion ? Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t KevinFirst Ow ens plor esion PL/isSQL, acle's answinert ht oe tADD h e Stpr r uct ur ed Langu age ( SQL) , an d , t heexexcept or ig Or inally r aised oced ur eQuery of ADD_ PKG. This t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. pr oced ur e has no ex cept ion h andler, so cont r ol j um ps t o an ex cep t ion handler in t he block of PROC_1. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag ecod of eOrinacle ur es such asler t rig and prclud ocedesurDBMS_OUTPUT. es- f eat u r es t hat Then allow tyher oure The t h e feat except ion hand isgers ex ecu t edst . ored This in dat abis ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he a RAI SE st at em en t . This ex it s t he cu rr ent block as an ex cept ion. Th e except ion bu sin pr ess evolv es.t oTopics cov est er edout include: opag at es t h e near er scop e block or p rocedur e. Ther e is an ex cept ion hand ler f or t he pr ocedu r e, b ut it is specif ic for a VALUE_ ERROR. ViewRAI in g SE const r aint s in datt haedict ionBEGI ar y N- BLOCK goes d ir ect ly t o t h e pr oced ur e t hat The st at em en t wt hitehin local called PROC_1. Com plex r ule enf orcem en t What if PROC_1 inclu ded a WHEN OTHERS except ion at t he pr ocedur e level? I n t his case, t he PL/ SQL p r ogr am un it s and langu age f eat u res RAI SE st at em ent w ould be caugh t in t he WHEN OTHER ex cep t ion p ar t of t h e pr oced ur e except ion hand ler . Dat a t y pes and comp osit e st r u ct u re Wit hin t he body of a PL/ SQL b lock or pr ocedu r e a RAI SE st at ement m ust b e follow ed b y an Er r or han dling and except ions except ion nam e. This sy nt ax is: I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e RAISE Pr ogr amexception_name; m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. The RAI SE st at em en t inside an ex cept ion han dler m ay be j ust t he RAI SE key w ord , t hat is: [ Team LiB ]

RAISE; [ Team LiB ] When RAI SE does not ident ify an ex cept ion n ame, t h e same ex cep t ion is r aised . How ever , an except ion hand ler may ex ecu t e a RAI SE st at em en t nam ing an except ion. I t can nam e t he sam e ex cep t ion of an ot her ex cept ion .

11.18.6 Unhandled Exceptions and Exception Propagation When an applicat ion raises an ex cep t ion t h at is n ot caug ht , it pr opag at es back t o t he app licat ion as an Or acle er r or. The Or acle err or is:



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

ORA-06510: PL/SQL: unhandled user-defined exception By Kevin Owens ThisPub is lish a er: serPrent iousice p rob lem becau se it does not ind icat e t he except ion nam e. Con sider t h e Hall PTR scenar io in w hich a Jav a p r ogr am calls p r ocedu re P1. P1 calls P2, w hich calls t h e pr oced ur e Pub Dat e: Decem ber 0 5, 2 003 ADD in t he pack age AD D_PKG. Assum e t h is r esult s in a ru n- t im e ZERO_AMOUNT ex cep t ion . I SBN: 0- 13 -0 850 33 -0 The b eh avior of t he except ion pr opag at ion is sh own in Figur e 11 - 11. Pages: 44 8

Figu r e 1 1 -1 1 . Exce pt ion Pr opaga t i on. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t What hap pens if P2 has an y of t he f ollowin g ex cept ion h andlers: PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] Ex ce pt i on H a nd le r in P2 EXCEPTION WHEN add_pkg.zero_amount THEN NULL; END;

Re sult P1 has n o idea an er ror occur r ed. Fr om P1' s per sp ect iv e, ev er yt h ing is nor m al.

Sam e as abov e. EXCEPTION WHEN OTHERS THEN NULL; END; •

Table of Content s

The ex cep t ion is p rop agat ed back t o P1 . I t m ay han dle it . I t may not .

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

EXCEPTION By KevinWHEN Owens add_pkg.zero_amount THEN RAISE; END; Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

Sam e as abov e.

I SBN: 0- 13 -0 850 33 -0

EXCEPTION Pages: 44 8 WHEN add_pkg.zero_amount THEN RAISE add_pkg.zero_amount; END; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Sam e. ur ed Query Langu age ( SQL) , an d Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er teo as t h eabov St r uct t EXCEPTION eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. WHEN OTHERS THEN Using easy-RAISE; t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our END; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include:

11.18.7 RAISE_APPLICATION_ERROR View in g const r aint s in t h e dat a dict ion ar y

RAI SE_ APPLI Com plexCATI r uleON_ERROR enf orcem enist a pr ocedu re in t h e Or acle built - in packag e DBMS_ STANDARD. Callin g t his pr oced ur e in you r code does n ot r aise an ex cep t ion . This pr oced urSQL e is included t he hlangu ead ing ex cep t ions b ecause, sim ilar t o ex cept ions, it PL/ p r ogr am un under it s and ageoff eat u res pr ov ides a m eans t o sig nal an er ror con dit ion. Except ions pr opagat e up t he PL/ SQL call chain.Dat Er arort yspes f r om RAI SE_APPLI do not pr opagat e. Th e follow ing par agr aph s and comp osit e CATI st r u ctON_ERROR u re cover t h e dif ferences bet w een RAI SE_APPLI CATI ON_ERROR an d ex cept ion s. Er r or han dling and except ions A Java applicat ion in clu des er r or - hand lin g cod e. The m et hod get Er r orCode( ) is a m ean s by w hichI nt t he a ap plicat r ealizes er -Jav pr ocess com ion mu nicat ionst h at an I NSERT or ot her D ML operat ion f ailed. There are m any r eason s w hy an Or acle err or shou ld occur . Som e ar e comm on , such as a const r aint at ivoteher const r aint s, including rim ar y kas ey ,a upnique, eign ion. k ey,Some ch eck are , and v iolat Declar ion , and s occur less fr eq uentply , such riv ileg feorviolat v ermyuch m en or et , such as w r it in g t o a t ablesp ace t hat is in READ ONLY m od e. inf requ Pr ogr am mt he ing scenar OracleioTrinigger s and St or edr ogr Pr oced ur es a , Th d Ed p it rion , is an inv. aluable r esou Con sider w hich a Jav ap am calls PL/irSQL ocedu re P1 Pr oced ur e P1rce for abase d esign and ojnt ecter leader inocedu g t o bre uild m taint callsdat P2. Th e druev n-elopers, t im e execut ionerofs,P2 enpr cou s an ersr look or . Pr P2an t rdies o wrain it e t trouly a int elligONLY en t , com dat abases. READ t ab plex lespace. Con t rol goes t o t he Jav a p rog r am w here it r eads t he er r or nu m ber as - 00 372 . The er r or m essage is: " f ile 8 can not be m odified at t his t im e. " Figur e 11 - 12 sh ows Team LiBior ] of execut ion. t[ hat behav

Figu r e 1 1 -1 2 . Or a cl e Er r or s.

[ Team LiB ]

PL/ SQL ex cep t ions pr opag at e w it hin PL/ SQL, bu t d o not pr opag at e out side t he lang uage. A PL/ SQL ex cep t ion t r an sf orm s in t o t h e Or acle er r or :



Table of Content s

Pr ogr am m ing OrPL/SQL: a cl e ® Tr i gger s and Stor euser-defined d P roce dure s, Thir d Edi ti on ORA-06510: unhandled exception By Kevin Owens

Sup pose you w ant t o com m un icat e an er ror con dit ion fr om t h e PL/ SQL w or ld t o t h e Jav a w orPub ld . lish You r aise an ex cept ion , bu t y ou can " r aise an applicat ion er r or" t hat assu mes t h e er: can't Prent ice Hall PTR behav an Orber acle r or . The int er face f or t h is is: Pubior Datof e: Decem 0 5, er 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

RAISE_APPLICATION_ERROR(ARG1, ARG2); Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. ARG1 Any n um ber w it hin t he ran ge ( - 2 099 9, - 2 0000 ) Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake ARG2 Test m Or essage in dicat g youas r ert rig r orgers and st ored pr oced ur es- f eat u r es t hat allow y our adv ant ag e of acle feat ur esinsuch dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin esst evolv es. Topics er ON_ERROR ed include: assu m es t he behav ior of an Or acle er r or . This As said, h e RAI SE_ APPLIcov CATI m ean s t hat a Java applicat ion can capt u re y our er r or code n um ber and t ex t m essage as an app licat ion er r or . View in g const r aint s in t h e dat a dict ion ar y I t also m eans t hat t he execut ion pat h im m ed iat ely leaves t h e PL/ SQL env ir onm en t an d Com plexerr sule cont r ol t r ansf d irenf ectorcem ly t o t en h et calling ap plicat ion , t hat being t he Java, C+ + , or ot h er langu age p rog ram . I n Figur e 11 - 13, p rocedur e P2 r aises an er ror t hat can be cau ght by t h e PL/ SQL p r ogr am un it s and langu age f eat u res app licat ion. The er ror num ber is - 2 000 0 an d t he er ror t ex t is " St udent cannot r eg ist er . Class is f ull." Dat a t y pes and comp osit e st r u ct u re Er r or han dling and Figu except r e 1ions 1 -1 3 .

Ra ise App li cat ion Er r or .

I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] The cod e in P2 w ould look like t he f ollow ing :

SELECT COUNT (*) INTO number_of_students FROM students_courses WHERE course_name = v_course_name; IF number_of_students >= 30 THEN RAISE_APPLICATION_ERROR (-20000, 'Student cannot register. Class full.'); END IF; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

11.18.8 EXCEPTION_INIT By Kevin Owens

Sup pose you w ant t o cap t ur e an Or acle er r or , locally . A d uplicat e insert on a p rim ar y k ey const r ain t v Prent iolatice ionHall raises Pub lish er: PTR an ex cep t ion. That except ion can b e capt ur ed. Th e err or f r om a check con st r aint v iolat ion does n ot r aise an ex cep t ion. A ch eck const r aint er r or is an Or acle Pub Dat e: Decem ber 0 5, 2 003 err or . Th e behav ior of an Or acle er ror is diff erent , as discussed in Sect ion 11 . 18. 7, I SBN: 0- 13 -0 850 33 -0 " RAI SE_ APPLI CATI ON_ERROR." Pages: 44 8

I n PL/ SQL, y ou can st ipulat e t h at a par t icular err or b e r aised as an ex cep t ion. To do t his y ou fir st d eclar e an ex cep t ion. Th en m ap t he ex cept ion t o t he er r or num b er . You m ust kn ow t he err or n um ber . The PL/ SQL st at ement used is a PRAGMA. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t The STUDENTS t ableeshPL/ as aSQL, CHECK con stansw raint eront ot he n. The colum n value Kevin Ow ens ex plor Or acle's t h eSTATUS St r uct urcolum ed Query Langu age ( SQL) mu , anstd be " Deg ryou ee" w orhat " Cer t if icat e. "t oThe f ollow pr rob ocedur capplex t ur edat a ch const ion. t eaches y ou n eed kn ow t o ing build ust e ancan d com abeck ases f or ryaint our bviolat usiness. I t d eclar es an ex cept ion CHECK_CONSTRAI NT_VI OLATI ON. Th at is m app ed t o t he er r or nu mb er for t ohefollow checkinst conr st r aint ditples, ionally, his pr pr ocedur ex cept Using easyuct ionserr anor d .exAd am t hist book esentes includes t echniq ues t o t ion akehan dling foracle a du plicat e such inser tas . t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our adv ant ag cod e ofeOr feat ur es dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y CREATE OR REPLACE PROCEDURE Com plex r ule enf orcem en t insert_student(v_stucent_id VARCHAR2, v_student_name VARCHAR2, PL/ SQL p r ogr am un it s and langu age f eat u res v_college_major VARCHAR2, v_status VARCHAR2, Dat a t y pes and comp osit e st r u ct u re v_state VARCHAR2, v_license_no VARCHAR2) Er r or han dling and except ions IS check_constraint_violation I nt er - pr ocess com mu nicat ions exception; pragma exception_init(check_constraint_violation, -2290); BEGINDeclar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch INSERT m or e INTO students VALUES (v_stucent_id, v_student_name, v_college_major, v_status, Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce v_state, v_license_no); for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. dbms_output.put_line('insert complete'); [ Team LiB ] EXCEPTION WHEN DUP_VAL_ON_INDEX THEN dbms_output.put_line('PK or unique const violation'); WHEN check_constraint_violation THEN

dbms_output.put_line('check constraint violation'); [ Team LiB ] END;

Ex cep t ions d o not pr opag at e out side of PL/ SQL. When unchecked, t hey become Or acle er ror :

ORA-06510: PL/SQL: unhandled user-defined exception

This p rocedur e m ap s an Or acle check const rain t er ror t o an except ion. What happ en s if t his pr oced ur e r aises t h e except ion, CHECK_ CONSTRAI NT_VI OLATI ON? That is, w hat h appens if t his ex cep t ion is r aised inside of PL/ SQL and is un cau ght w it hin PL/ SQL? Th e applicat ion t hat •called t his p rocedur Table of Content e g et s st he er r or cod e of a check const r ain t v iolat ion, m inu s 229 0. I t does Pr ogr am m ing Or a cl e ® Tr s at andu Stor e d P roce dure s, Thir d Edi on ions r esult in Or acle 065 10 er r or s. not get 0651 0. I t is t ri gger ue t h ncaugh t user - defined ex ticept But Or acle er r or s m apped t o ex cept ion s t hr oug h PRAGMA EXCEPTI ON_ I NI T, w h en t h ey By Kevin Owens pr opag at e and ar e un cau ght , r esult in t h e or iginal Oracle err or . [ Team LiB Pub lish er: ]Prent ice

Hall PTR

Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.19 Database Access with SQL 11.19.1 Cursor FOR LOOPS The cu rsor FOR LOOP r equir es use of SQL and a PL/ SQL FOR LOOP. This is a sim ple ap pr oach t o quer yin g t h e dat ab ase. You can con st ru ct a cur sor f or loop usin g any v alid SQL st at em en t . The sy nt ax is: •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

FORyour_name IN (SELECT rest of SQL statement LOOP your_name.column_name is defined here Pub lish er: Prent ice Hall PTR END LOOP; Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages:in44 The f ollow g 8b lock select s all st u dent nam es and t he sum of t heir par k ing t ick et s. The LOOP t em por ary var iable, REC, only ex ist s for t he du rat ion of t h e LOOP. Wit hin t he loop w e can access colum ns in t he q uer y t hr oug h t h e r ecor d, REC.

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. BEGIN Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake FOR INacle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our adv ant ag erec of Or student_name, sum(amount) parking_ticket_total dat ab ases(SELECT t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he FROM students bu sin ess evolv es. Topics cov era, ed include: student_vehicles b, parking_tickets c View in gWHERE const ra.student_id aint s in t h e dat a ion ar y = dict b.student_id AND b.state=c.state and b.tag_no=c.tag_no Com plex r ule orcem en t GROUP BY enf student_name) LOOP PL/ SQL p r ogr am un it s and langu age f eat u res dbms_output.put_line (rec.student_name||' '||rec.parking_ticket_total); Dat a t y pes and comp osit e st r u ct u re END LOOP; END; Er r or han dling and except ions I nt er - pr ocess com mu nicat ions The ag gr egat e f unct ion, SUM, requ ires a colu mn alias t o resolve an at t r ibu t e nam e f or t he r ecor d. Lit erals d ex pr essions m ust hav e aarcolum aliask ey, is t hen u sed to m select Declar at iv eanconst r aint s, including p rim y k ey ,n ualias. nique,That f or eign ch eck , and uch t he com pon m or e en t v alue f r om t he r ecord . IPrf ogr t he am SQL q uery has Tr a igger zer o sresult set i. e.Pr, oced no r ows ned) loop s gr acef ully. m ing Oracle and St or(ed ur es are , Thret ir durEd it ion, ,t he is an invexit aluable r esou rce Therdat e is no exdcept ion con ddit ion raised. for abase ev elopers, esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. The cu rsor can be d eclar ed in t he d eclar at ive p art . The loop r ef erences t he cu rsor v ar iable. [ Team LiB ]

DECLARE [ Team LiB ] CURSOR C1 IS SELECT student_name, sum(amount) parking_ticket_total FROM students a, student_vehicles b, parking_tickets c WHERE a.student_id = b.student_id AND b.state=c.state and b.tag_no=c.tag_no GROUP BY student_name; BEGIN FOR rec IN C1 LOOP dbms_output.put_line (rec.student_name||' '||rec.parking_ticket_total); END LOOP; END; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

11.19.2 Select When Expecting a Single Row By Kevin Owens You can ex pect a sing le row w hen t he qu er y includ es a pr im ar y key . The p ossibilit y d oes ex ist er: Prent iceur Hall PTR h is wou ld occur if n o r ow exist s w it h t hat pr im ar y key v alue. t hatPub nolishr ow is r et ned—t Pub Dat e: Decem ber 0 5, 2 003

I f no row s ar0-e13r-0 et850 ur ned I SBN: 33 -0 t he NO_ DATA_FOUND ex cep t ion is r aised . I f t her e sh ould be m ult iple r ow s, Pages: t he ex44 cept ion TOO_MANY_ROWS is r aised . 8 The on ly w ay t his w ou ld occur w ould be if t h e pr im ary key const r aint w as disab led and du plicat e dat a was load ed . Ef fect ively increat d ed man comeplex abases w it hleOr acle! st e ems and ab ase The f ollow g is ea an st or prage ocedur t h at dat select s a sing r ow. I f Sy m or t h an ondat e r ow is ex per t Kevin Ow tens ex plor ion es PL/ acle's answ t o tr how e sStar r uct Query SQL) , an d r et ur ned he except is rSQL, aisedOrand caugh t . er I f no e rur et ed ur ned t heLangu ex ceptage ion (is r aised tand eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. caugh t . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: CREATE OR REPLACE PROCEDURE get_student_major View(v_student_id in g const r aint s in IN t h e dat a dict ion ar y students.student_id%TYPE, v_name OUT students.student_name%TYPE) IS Com plex r ule enf orcem en t BEGIN SELECT student_name PL/ SQL p r ogr am un it s and langu age f eat u res INTO v_name FROM students Dat a t y pes and comp osit e st r u ct u re WHERE student_id = v_student_id; exception Er r or han dling and except ions WHEN TOO_MANY_ROWS THEN dbms_output.put_line('TMR error'); WHEN THENions dbms_output.put_line('NDF error'); I nt er -NO_DATA_FOUND pr ocess com mu nicat END; Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e

11.19.3 Updates Pr ogr am m Inserts ing Oracle and Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig t , com abases. I nser t sen and updplex at e stdat at ement s in PL/ SQL ar e ver y similar t o execut ing SQL in an in t er act iv e env iron ment like SQL* Plu s. The f unct ion SQL% ROWCOUNT is u sef ul af t er upd at e st at em en t s. [ Team LiB ] SQL%ROWCOUNT This f unct ion evaluat es t o t h e num ber of r ow s af fect ed by t he last I NSERT and UPDATE. I t equals zer o if no r ows w er e chang ed .

[The Team LiBin]g f un ct ion up dat es pr of essor salaries and r et ur ns t h e nu mb er of row s u pdat ed. f ollow The t yp e of t he r et ur n ar gum ent is NATURAL because t h e num ber of u pdat ed r ow s w ill alw ay s be z er o or gr eat er .

CREATE OR REPLACE FUNCTION update_salaries(new_sal IN professors.salary%TYPE) RETURN NATURAL IS BEGIN UPDATE professors2 SET salary = new_sal; RETURN SQL%ROWCOUNT; END update_salaries; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

Use % ROWTYPE t o pass m ult iple com ponent s t o a su bpr ogr am . Th is pr ocedu re in ser t s a By Kevin Owens st udent and accep t s a % ROWTYPE as a sin gle par am et er . Th e STUD ENT_I D is not in clu ded in t he orig in al r ecor d. That is g en er at ed as a sequ en ce n um ber . This p rocedur e inser t s t he st udent and r et ur ns t h e STUDENT_I D as par t of t he r ecor d. Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003

A let t er " A" is a p refix f or t h e seq uence num ber . Th e sam p le dat a f r om Ch apt er 4 in clu des 0- 13 -0 850s33 -0 begin w it h a let t er. This is in keeping w it h t hat con vent ion . st udentI SBN: I D num ber t hat Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t CREATE Kevin OwOR ensREPLACE ex plor esPROCEDURE PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d add_student(rec IN OUT IScom plex dat ab ases f or y our b usiness. t eaches you w hat y ou n eed t o knstudents%ROWTYPE) ow t o build rob ust an d BEGIN 'A'||students_pk_seq.nextval UsingSELECT easy- t ofollow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake INTO adv ant ag e of rec.student_id Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our FROM dat ab ases t o dual; incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: INSERT INTO students (student_id, student_name, college_major, status, state, license_no) View in g (rec.student_id, const r aint s in t h e dat a dict ion ar y VALUES rec.student_name, rec.college_major, rec.status, Com rec.state, plex r ule enf orcem en t rec.license_no); END add_student; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re This p rocedur e d oes an in ser t . Wh y does it n eed t o r et ur n t he r ecord ? Wh y can't REC b e I N r at her t h an I N OUT? Er r or han dling and except ions I t d ep en ds on t he agr eem ent b et ween t he p rog ram m er of ADD_ STUDENT and t h ose wh o call I nt er - pr ocess com mu nicat ions t his p r ocedu re—t h at m ay be t he sam e pr ogr am m er . Th e calling p rocedur e m ay n eed t he STUDENT_I t oeinconst ser t raaint r ecor d in t h e child abyle. One op t ion f is t o pass STUDENT_ IDm back Declar D at iv s, including p rimtar k ey , u nique, or eign k ey, ch eck , and uch t o t he caller using t he sam e r ecor d. The I N OUT mod e allow s t he caller t o g et t he STUDENT_ ID m or e t hat w as add ed t o t he r ecord by t his pr ocedur e. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce An alt nat iv ed ev is elopers, f or t he prdocedu r es,t oand inser e st udents and D frtom for daterabase esign er prtojt hect leader look rinetgurt on bt he uildSTUDENT_I an d m aint ain r ulya fu nct ion. Th is w ould be a sligh t ly diff erent calling int er face. I n eit h er case t h e caller has t he int ellig en t , com plex dat abases. new STUDENT_ I D f or add it ion al use. The f ollow in g is an int er f ace f or insert in g a st udent and a st u dent Refer t o t he DD L in Ch apt er 4 t hat sh ows t he d at a m odel. I n t his m odel [ Team LiBvehicle. ] STUDENT_VEHI CLES is a child t o STUDENTS. A specificat ion for ad ding st udent inf orm at ion is t he follow in g. Th is is a p ack age specificat ion t hat add s a st u dent an d adds a st udent v eh icle.

[ Team LiB ]

CREATE OR REPLACE PACKAGE students_pkg IS FUNCTION add_student(rec IN students%ROWTYPE) RETURN students.student_id%TYPE; PROCEDURE add_vehicle(rec IN student_vehicles%ROWTYPE); END;

The u ser of t his pack age m ust fir st call ADD_ STUDENT and t h en call ADD_ VEHI CLE. Pr ior t o callin g AD D_VEHI CLE, t h e STUD ENT_I D m ust b e added t o t he v eh icle r ecor d—below t his is t he assign ment pr ior t o calling ADD_ VEHI CLE. This enf or ces r efer en t ial int egr it y —t he •STUDENT_I DTable s eign key t o t he STUDENTS t able. coluofmContent n is a for Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

The u ser of t he pr ecedin g p ack age w ould h ave PL/ SQL logic sim ilar t o t h e follow ing. By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 DECLARE Pages: 44 8 students%ROWTYPE; student vehicle student_vehicles%ROWTYPE; BEGIN student.student_name := 'Jack'; Ef fectstudent.college_major ively creat e an d man age com := 'HI'; plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t :=acle's 'Degree'; Kevinstudent.status Ow ens ex plor es PL/ SQL, Or answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches student.state you w hat y ou n eed t o kn :=ow'CA'; t o build rob ust an d com plex dat ab ases f or y our b usiness. student.license_no := 'MV-232-14'; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our student.student_id :=such students_pkg.add_student(student); dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sinvehicle.state ess evolv es. Topics cov er ed include: := 'CA'; vehicle.tag_no := 'CA-1234'; vehicle.vehicle_desc := 'Mustang'; View in g const r aint s in t h e dat a dict ion ar y vehicle.parking_sticker := 'A-101';

Com plex r ule enf orcem en t vehicle.student_id := student.student_id; PL/ SQL p r ogr am un it s and langu age f eat u res students_pkg.add_vehicle(vehicle); END; Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions The b ody f or t he STUDENTS_PKG is sh ow n n ex t . I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m CREATE ORing REPLACE Oracle Tr PACKAGE igger s and BODY St orstudents_pkg ed Pr oced ur es ,IS Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig FUNCTION en t , com plex add_student(rec dat abases. IN students%ROWTYPE) RETURN students.student_id%TYPE [ Team IS LiB ] ID students.student_id%TYPE; BEGIN SELECT 'A'||students_pk_seq.nextval INTO ID FROM dual;

[ Team LiB INSERT ] INTO students (student_id, student_name, college_major, status, state, license_no) VALUES (ID, rec.student_name, rec.college_major, rec.status, rec.state, rec.license_no); RETURN ID; END add_student; PROCEDURE add_vehicle(rec IN student_vehicles%ROWTYPE) IS BEGIN INSERT INTO student_vehicles (state, tag_no, vehicle_desc, student_id, parking_sticker) VALUES (rec.state, rec.tag_no, rec.vehicle_desc, rec.student_id, rec.parking_sticker); END add_vehicle; END students_pkg; • Table of Content s Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

11.19.4 Explicit Cursors Pub lish er: Prent ice Hall PTR

Ex plicit cur sors follow a DO- WHI LE- DO loop m odel; t hat is: Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

OPEN cursor LOOP Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t record KevinFETCH Ow ensa ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d EXIT row returned. t eaches youWHEN w hatno y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Process this fetched row. UsingLOOP; easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake END adv antcursor ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CLOSE dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: The cu rsor - for loop , discussed pr eviously , is a sim ple app r oach t o quer yin g t he dat ab ase. Th e cur sor- f or loop generally h as bet t er per for m ance t han ex plicit cu r sor s. How ever , an ex plicit in g r aint in riat t h e edat arlar y algor it hm . The follow ing discu ssion sh ow s cur sorView m ay beconst m or e appsrop fora adict parion t icu t he main f eat u res of an exp licit cu rsor . Then an ex am ple is show n. Com plex r ule enf orcem en t An ex plicit cur sor r eq uir es a cur sor definit ion . This is a SQL st at em ent and a cur sor v ar iab le. PL/ SQL une itiss declared. and langu The age dat f eatat u res A cur sor r ecorpdr ogr st r am uct ur yp e of t he cur sor r ecor d is der iv ed fr om t h e cur sor definit ion . Dat a t y pes and comp osit e st r u ct u re The f ollow in g PL/ SQL block declares a cu rsor t hat j oins t ab les STATE_LOOKUP and Er r or han dling and except ions STUDENTS. To m ake t his int er est ing , t he f ollow in g f eat ur es are in corp orat ed int o t he PL/ SQL block :I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch REPLACE and NVL fu nct ions ar e used. Th ese f unct ions replace a dash w it h a sp ace in t h e m or e st udent license n um ber . Also, t he st r ing " None" is r eplaced w it h a NULL should t her e be license. A st rTr ing " N/sA"and r eplaces if tur h er Pr ogr no am m ing Oracle igger St or edNULL Pr oced ese, is Thnirod st Edatite. ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly The SQL st at em ent in t h e cur sor uses an ou t er join. This is necessar y t o includ e st udent s int ellig en t , com plex dat abases. w ho hav e a NULL st at e colum n value. Not all st ud en t s hav e a license; hence t h eir STATE v alue [ Team LiB is ] NULL. The STUDENTS is joined w it h STATE_LOOKUP on t he STATE colu m n. The plus operat or ( + ) is ap pended t o t he STUDENTS t able in t he FROM clause. The r ow s ar e f et ch ed and copied in t o a global t em por ar y t ab le. Af t er t he scr ipt , t h e t able is q uer ied for out pu t . The scr ipt cou ld u se D BMS_OUTPUT, but t her e is a buf fer

limit at ]ion t o DBMS_OUTPUT. Th e t em p orar y t ab le is m ore ap pr opr iat e f or spooling lar g e [ Team LiB am ount s of dat a.

DROP TABLE TEMP; CREATE GLOBAL TEMPORARY TABLE temp (name VARCHAR2(10), state VARCHAR2(15), license VARCHAR2(20)); DECLARE CURSOR student_cursor IS SELECT a.student_name, NVL(b.state_desc, 'N/A') state_desc, NVL(REPLACE(a.license_no,'-',' '), 'None') Lic • of Content s FROM Table students a, state_lookup b Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on WHERE a.state = b.state(+); By Kevin Owens

student_cursor_rec student_cursor%ROWTYPE; BEGIN Pub lish er: Prent ice Hall PTR Pub OPEN Dat e:student_cursor; Decem ber 0 5, 2 003

LOOP I SBN: 0- 13 -0 850 33 -0 FETCH student_cursor INTO student_cursor_rec; Pages: 44 8 EXIT WHEN student_cursor%NOTFOUND; INSERT INTO temp VALUES Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t (student_cursor_rec.student_name, Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d student_cursor_rec.state_desc, t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. student_cursor_rec.lic); LOOP; UsingEND easyt o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake CLOSE adv ant ag e ofstudent_cursor; Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our END; dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SELECT * FROM TEMP; View in g const r aint s in t h e dat a dict ion ar y This PL/ SQL block exit s t he loop on t he evalu at ion of : % NOTFOUND. This cur sor at t r ibut e is TRUECom or FALSE andenf should aft er each fet ch. An exp licit cu rsor h as t he f ollowin g plex r ule orcembe enchecked t at t r ibut es: PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes comp osit e or st r FALSE u ct u re b ased on t he last f et ch . %NOTFOUND Thisand r et ur ns TRUE %FOUND Er r or han The dling n egand at ion except of % ions NOTFOUND. %ROWCOUNT t rib ut e nicat r et urions ns t h e nu mb er of row s f et ch ed so f ar . I t can be called I nt er - pr This ocessatcom mu any t im e aft er t he f ir st f et ch . This at t rib ut e also r et ur ns t h e nu mb er of row s ed frr om andpDELETE en t s. f or eign k ey, ch eck , and m uch Declar ataff iv eect const aint UPDATE s, including rim ar y kst eyat, em u nique, m or e %ISOPEN Ret ur ns TRUE if a cu rsor is st ill op en . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce A cur sor can be aram et er dr iven. ing leader block sd eclar esg at ocur sor an t hat joins t he t r uly for dat abase d evpelopers, d esign er s,The andf ollow pr oj ect look in b uild dm aint ain STUDENTS an d STATE_LOOKUP t able, b ut only for st u dent s w it h a p ar t icu lar STATUS. Th at int ellig en t , com plex dat abases. STATUS is det er min ed w hen t he cur sor is opened. This exam p le opens t he cu rsor u sin g a lit er al stLiB r ing] , " Degr ee. " [ Team

[ Team LiB ] DECLARE CURSOR SELECT

FROM WHERE AND

student_cursor (v_student_status students.status%type) IS a.student_name, NVL(b.state_desc, 'N/A') state_desc, NVL(REPLACE(a.license_no,'-',' '), 'None') Lic students a, state_lookup b a.state = b.state(+) a.status = v_student_status;

student_cursor_rec student_cursor%ROWTYPE; BEGIN OPEN student_cursor('Degree'); LOOP Table of Content s FETCH student_cursor INTO student_cursor_rec;



Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens EXIT

WHEN student_cursor%NOTFOUND;

INSERT INTO temp VALUES Pub lish er: Prent ice Hall PTR (student_cursor_rec.student_name, Pub Dat e: Decem ber 0 5, 2 003 student_cursor_rec.state_desc, I SBN: 0- 13 -0 student_cursor_rec.lic); 850 33 -0 END LOOP; Pages: 44 8 CLOSE student_cursor;

END; Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t [Kevin TeamOw LiB ] ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d ens t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.20 Sending Pipe Messages (DBMS_PIPE) Or acle' s DBMS_ PI PE p ack age is an API t o a set of p r ocedu res an d f unct ions t hat su ppor t com mu nicat ion b et w een t wo or m or e pr ocesses con nect ed t o t he sam e Or acle in st ance. Or acle pipes ar e half - diplex. Dat a flow s in one dir ect ion . Figur e 11 - 14 illust r at es a sing le pipe for a on e- w ay d ir ect ional f low of inf orm at ion bet w een t w o Oracle p rocesses connect ed t o t he sam e inst ance.

Figu r e 1 1 -1 4 . Basic Pip e. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

I n Figur e 11 - 14, p rocess P1 send s dat a t o P2 . You need a second pipe f or P2 t o send dat a back t o P1. Consider P1 t o b e ru nnin g on a dedicat ed piece of har dw ar e and connect ed t o an Or acle inst ance. The ot h er applicat ion, P2, cou ld r esid e on anot her ser ver . Bot h applicat ions Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t ar e connect ed t o t he sam e dat abase inst ance. The com m unicat ion is asy nchr onou s. Wr it er s Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d do not w ait f or r ead er s and r eaders do n ot h ave t o w ait f or w r it er s. t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Messag es going int o t he pip e can or iginat e fr om m ult iple sour ces. Remot e applicat ions can Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake init iat e p rocedur e calls t o D BMS_PI PE t hr oug h ODBC, JD BC, or Net 8. Messages can also adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our or iginat e f r om dat ab ase t rig gers. Th er e can be an y num ber of m essag e pr oducer s t hat inser t dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he m essages int o t he p ipe. Lik ew ise, t her e can b e any n um ber of m essage consu mer s t hat r ead bu sin ess evolv es. Topics cov er ed include: m essages f rom t he p ip e. The pip e is a FI FO st r uct ur e. Messag es in sent t o a rdat aset hpipe notion t r ar ansact ion b ased. The m essage pr oducer , aft er View g const aintab s in e datar a edict y sen ding t he message, m ig ht do a comm it or it m igh t d o a rollback ; eit her w ay , t hat m essage r em ains t h e rpipe. Thorcem is mechanism is d iffer ent fr om dat ab ase aler t s, im plement ed w it h t he Cominplex ule enf en t Or acle DBMS_ALERT pack age—aler t s ar e t r ansact ion based . I f a pr ocess send s an aler t an d t hen rPL/ ollsSQL back, t heam alert oided. p r ogr un itiss vand langu age f eat u res You wDat ill be t w o comp su bprosit ogream a t using y pes and st rsuin ct ut he re p ack age: PACK_MESSAGE and UNPACK_MESSAGE—t h in k of a m essag e par t r at h er t han t he w h ole messag e. A p rod ucer can call PACK_MESSAGE 10 texcept im es, each Er r or han dling and ions t ime placin g a t ext st r in g in t o a local buf fer . The p ack ing is f ollow ed by a sing le SEND_MESSAGE. The r eceiv er issues one RECEI VE_MESSAGE, w hich I ntfollow er - pr ed ocess comUNPACK_MESSAGE mu nicat ions can be by 10 calls. Con sider t he un packin g t o be u npack ing 10 m essage p art s. The k ey is t hat message par t s can v ary in d at at yp e. One p ar t can be a DATE at ivaeVARCHAR2 const r aint s,t yincluding p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch t y pe; Declar an ot her pe. m or e You can com bine d at at y pes t o for m a sing le m essage. The PACK_MESSAGE p rocedur e is Pr am m ingsoOracle Tr igger s and St or ed ocedp ur es a, Th ir d Ed itpion invNUMBER, aluable r esou ovogr er loaded, is UNPACK_MESSAGE. YouPrcan ack m essage ar ,t is of an t y pe t henrce a for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly t y pe of VARCHAR2 t yp e, and a D ATE. The receiv er of a m essag e can " p eek " int o t he pipe int ellig en tt,ocom plex m essage det er mindat e tabases. he d at at y pe of t he next m essage p art . [ Team LiB ]

11.20.1 Send-Receive Example

The f ollow [ Team LiBin]g p ar agr aphs d escr ibe and illust r at e, w it h PL/ SQL pr oced ur es, a desig n in w hich pr ocesses can com m unicat e in a b id irect ional m ode. Th is gener alizat ion of comm u nicat ion w it h pipes can be a b asis for solv in g r eal- w orld specif ic pr oblem s w it h p ipes. A g r oup of pr ocesses can comm u nicat e w it h each ot her by cr eat ing a " h ome" pipe f or each pr ocess—similar t o a m ailbox f or a house. Each pr ocess pu lls messages out of t heir hom e pipe. Each p rocess kn ow s t he n ame of all ot her pip es an d can send messages t o t h ose ot her hom e p ip es. Figur e 11 - 15 illust r at es t his com m unicat ion mod el.

Figu r e 1 1 -1 5 . M ul t ip le Pr oce sses a n d Pip es.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

I n a f lu id sit uat ion , w her e pr ocesses com e and g o, a sof t w are ar chit ect ur e can dy nam ically gener at e pip e nam es w it h t h e DBMS_ PI PE f unct ion, UNI QUE_SESSI ON_ NAME. Th is fu nct ion r et ur ns a pipe n ame t hat is guar ant eed t o b e uniq ue w it hin t he in st an ce. ively an d pman agehas comaplex abases it h Or acle! Sy st emsPrand datP1 ab ase per t IEfnfect Figur e 11creat - 15, eeach r ocess homdat e pip e for w receiv ing m essages. ocess can ex send Kevin Ow ens answ erTht oe tsam h e St ur ed Langu ( SQL) , an d m essages t o tex heplor p ipes es PL/ of tSQL, he ot Or h eracle's pr ocesses. e rhuct olds f or Query pr ocess P2. age When pr ocess tP1 eaches w ,hat y ou n eed t o kn build rob ust anmd echan com plex ases f or y our b usiness. is notyou busy it issues a r ead onow it st ohom e pipe. Th e ism dat for ab r eading am essag e is t o issu e a r ead- w ait w it h a t im er ex pr essed in second s. A pr ocess can poll a pipe by set t ing t he Using o-Ot follow ions ex am pr esent ues t o rt eceiv ake es t im er teasyo zer to. h er winst ise,r uct a t im er an in dsecon dsples, w ill tphis ost book a r eadw ait . sAt echniq pr ocess t h at adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur esf eat u r es t hat pipe messages is gener ally d ed icat ed t o ser vicing pipe m essag es only. When t her e allow is no y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he m essage in a pipe, t he pr ocess sit s in an idle st at e wait in g f or t h e next pipe message. bu sin ess evolv es. Topics cov er ed include: The f ollow in g p ar agr aphs illust r at e t h e code for P1 and P2. I n t his ex amp le, a pr ocedur e called P1 builds t w o m essage p art s and issu es a sen d t o a p ipe called HOME_OF_P2 . A View g const r aint in st ht he e dat a dict ion ar ysends a r ep ly back t o P1 u sing t h e pipe n am ed pr oced ur e,innam ed P2 , r sead message and HOME_OF_P1 . This code d em on st r at es t h e com m un icat ion illust rat ed in Figur e 11 - 15. Com plex r ule enf orcem en t Perf or m t he follow in g st eps t o d em onst r at e t h is com m un icat ion. Fir st com pile and ex ecut e PL/ SQL p r ogr am un it s and langu age f eat u res t he receiv er, P2. Wh en y ou ex ecu t e P2, t he p rocedur e p ost s a r ead- w ait w it h a 6 0- sec. t im eou t . a t y pes and comp osit e st r u ct u re Dat The CREATE dat abase screxcept ipt CATPROC. SQL does not gr ant EXECUTE on DBMS_PI PE t o pub lic Er r or han dling and ions as it does w it h D BMS_OUTPUT and m any ot her pack ages. You n eed t he ex ecu t e gr ant t o u se t he packag I nt er - e. pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e 1 . Con nect as SYS and GRANT EXECUTE ON D BMS_PI PE TO SCOTT. Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce 2 . Con nect as SCOTT. for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int3ellig en t pile , com abases. . Com P1plex anddat P2. [ Team LiB ] as SCOTT using SQL* Plus. 4 . Con nect 5 . SET SERVEROUTPUT ON. 6.

6 . Ex ecu [ Team LiB t]e P2—y our session w ill han g b ecau se y ou hav e issu ed a read- w ait on you r hom e pipe. Th e r ead - w ait is f or 60 sec. I f no m essage is sent fr om P1 in t hat t ime, t h er e w ill be a har m less er ror generat ed —w e' ll t alk abou t p ip e err or s shor t ly . Bef or e t he 6 0 sec is up , y ou n eed t o p er f orm t he n ex t t hr ee st ep s. 7 . St ar t a new SQL* Plus session . 8 . SET SERVEROUTPUT ON. 9 . Ex ecu t e P1—t his st ar t s t he p r ocess by sendin g a m essage t o t he h om e of P2. Af t er sen ding t he message, t he p rocedu re issues a r ead- w ait ( for 6 0 sec) on it s hom e p ipe. The f ollow in g is t he PL/ SQL cod e for pr ocedu res P1 and P2 .



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

CREATE OR REPLACE PROCEDURE P1 By Kevin Owens is status integer; response varchar2(2000); Pub lish er: Prent ice Hall PTR begin Pub Dat e: Decem ber 0 5, 2 003 dbms_pipe.reset_buffer; I SBN: 0- 13 -0 850 33 -0 dbms_pipe.pack_message('This is message 1'); Pages: 44 8 dbms_pipe.pack_message('This is message 2'); status := dbms_pipe.send_message('HOME_OF_P2'); status := dbms_pipe.receive_message('HOME_OF_P1', 60); dbms_pipe.unpack_message(response); Ef fectdbms_output.put_line('P1 ively creat e an d man age com received:'||response); plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t end KevinP1; Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. CREATE OR REPLACE procedure P2 Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake is adv ant ag e of Or acle integer; feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our status dat abmessage_1 ases t o incor porvarchar2(2000); at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sinmessage_2 ess evolv es. Topics cov er ed include: varchar2(2000); begin status := dbms_pipe.receive_message('HOME_OF_P2', 60); View in g const r aint s in t h e dat a dict ion ar y dbms_pipe.unpack_message(message_1); dbms_pipe.unpack_message(message_2); Com plex r ule enf orcem en t dbms_pipe.pack_message('Got your messages.'); status dbms_pipe.send_message('HOME_OF_P1'); PL/ SQL p:= r ogr am un it s and langu age f eat u res dbms_output.put_line('P2 received:'||message_1); dbms_output.put_line('P2 Dat a t y pes and comp osit e st r ureceived:'||message_2); ct u re end P2; Er r or han dling and except ions The session p ut com for t mu h e nicat P2, wh ich is ex ecut ed fir st , is t h e follow ing. I nt er - prout ocess ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce SQL> serveroutput for datset abase d ev elopers, d on esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int SQL> elligexecute en t , com plex p2 dat abases. P2 received:This is message 1 [ Team LiB ] P2 received:This is message 2

The session out p ut for t h e P1 is:

[ Team LiB ]

SQL> set serveroutput on SQL> execute p1 P1 received:Got your messages.

11.20.2 Interface Description The f ollow in g p ar agr aphs d escr ibe t he DBMS_PI PE pack age API .



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens PACK_MESSAGE

PROCEDURE pack_message(item in VARCHAR2); Pub lish er: Prent ice Hall PTR PROCEDURE pack_message(item in NUMBER); PROCEDURE pack_messge(item in DATE); Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

item This is a VARCHAR2, NUMBER, or DATE t y pe v ar iab le t hat is placed int o a local b uff er. You can p ack a single b uff er w it h sever al m essages, each of a diff erent t y pe. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t The D BMS_PI PEplor packag e pr ov ides over loaded res f orurpack ing diff er entage dat at y pes. You Kevin Ow ens ex es PL/ SQL, Or acle's answ erp troocedu t h e St r uct ed Query Langu ( SQL) , an d can packyou RAW andy LONG datt oat kn y pes. modrob el for g dplex at a tdat o aab p ipe o PACK e or t eaches w hat ou n eed ow tThe o build ust send an d in com asesisf tor y our bon usiness. m or e t imes, t h en SEND once. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake The PACK_MESSAGE p r ocedu copas iest rig d atgers a t o and a p rocessOresacle y buallow ff er . Each adv ant ag e of Or acle feat ur es re such st ored specific pr oced ur f eatmuem r esort hat y our Or con nect ion por h asataebbu uffsiness er available f or 40 ar 96eby t es tof a.age This bu m ff er can bet he p acked in datacle ab ases t o incor r ules w hich easy o dat man and odif y as st om d iffer ent pr ogr it hin a single Or acle connect ed session. Pack ing a m essag e buages, sin essfr evolv es. Topics covams er edwinclude: is not t he sam e as sendin g a m essage t o a p ipe. Sev er al m essages can be pack ed an d b e follow ed by a sing le send , w hich will p lace all packed m essages in t he d est inat ion bu ff er . On ce View a bu in ff er g const h as mr aint essages s in t h f rom e dataaPACK_ dict ionMESSAGE ar y call, t her e ar e t hr ee ev ent s t hat can occu r : Com plex r ule enf orcem en t PL/ SQL The p r ocess p r ogrdiscon am unnect it s and s fr om langu Oracle age fand eat unres o m essages ar e sen t . Dat ap tryocess The pes and callscomp D BMS_PI osit e st PE. r uRESET_BUFFER, ct u re w hich clear s t he b uf fer of all m essages. The Er r orp rhan ocess dling calls and D BMS_PI except ions PE. SEND_ MESSAGE, w hich send s all m essages and clear s t he bu ff er . I nt er - pr ocess com mu nicat ions I f you PACK w it hout int er ru pt ion, you w ill ov er f low t he 4 096 lim it at ion. This over flow at iv eatconst s,06 including p rim ar ilarly y k ey,, wu hen nique, eign k ey, ch fer eck ,wand m unp uch ack conditDeclar ion gener es anr aint ORA558 er ror . Sim w ef or UNPACK a buf e can an emmpor t y ebu ffer an d get an un derf low condit ion. Pr ogr am m con ing tOracle s and orted d Ed ion , is an aluable rce When t he en t s ofTra igger b uf fer ar e St sen t o Pr a oced p ip e,urt es hat, Th bufirfer is itcleared. Forinvex am ple,r esou you can for abase ev elopers, er s,b uf and oj ect s look in gt ot oa bpipe. uild an d mcan aintcall ain t r uly packdat 4 096 bydt es int o you rd esign session fer pr and senleader d t hese by t es You int ellig MESSAGE en t , com plex dat abases. PACK_ again, packin g an ot her 40 96 by t es. This second b uff er can b e sent . You hav e t o be car ef ul; y ou hav e ph ysical limit at ion s w hen send in g dat a t o a pipe. When y ou send a [fuTeam LiBt o] a pipe an d t h e r eceiver h as not read it s hom e p ip e, you r nex t send w ill hav e t o ll bu ff er w ait f or t he receiv er t o read it s hom e p ip e.

[ Team LiB ] SEND_MESSAGE FUNCTION send_message( pipename in VARCHAR2, timeout IN INTEGER DEFAULT maxwait, maxpipesize IN INTEGER DEFAULT 8192) RETURN INTEGER; maxwait constant integer := 86400000;

/* 1000 days */

RETURN INTEGER values: 0 – Success. 1 – Timeout because the pipe stays full leaving no room, or the sending process cannot place a lock on the pipe. • Table of Content s 3 Interrupted. Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

pipename Pub lish er: Pub Dat e:

This p aram et er is t he nam e of t he p ipe t h at is t o r eceiv e all m essag es pr esent in t he local b uff er . Pip e nam es ar e lim it ed t o 1 28 ch ar act er s. Do not Decem ber 0 5, 2 003 use p ip e nam es beginn in g wit h ORA$ as t hese are reser v ed b y Or acle. Prent ice Hall PTR

I SBN: 0- 13 -0 850 33 -0

This is an op t ion al ar gu ment t hat is t he t ime allow ed for m ov ing t he b uff er cont ent s t o t h e pipe. This is not t he t im e limit placed on a pr ocess r ead ing t he message. I f a pr ocess is slow in r ead ing m essages fr om it s hom e pipe ( i. e. , slow com par ed t o t h e rat e at w h ich dat a is flow ing int o t he p ipe, t he f ull; hence SEND_ MESSAGE w ill w f or r oom t o be m ade. If t Ef fect ively creatpipe e an dmay manbe age com plex adat abases w it h Or acle! Syait st ems and dat ab ase ex per oomesinPL/ t he p ip eOrisacle's not fransw eed , er t h et ot imer and t he m essag is not, an d Kevin Ow ens exrplor SQL, t h e Stwrill uctex urpir edeQuery Langu age e( SQL) senytou . n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. t eaches you w hat timeout Pages:

44 8

maxpipesize This is t he m axim um size m essag e allowed for t he p ip e. This m ust b e at least Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake as lar ge as t he m essage. Su bseq uent calls t o SEND_MESSAGE w it h a lar ger adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our m axp ipesize w ill incr ease t he m ax im u m size of a m essage allow ed in t h e dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he pipe. Maxp ip esize, w hen used , becom es a per sist ent at t r ibut e of t he pipe. bu sin ess evolv es. Topics cov er ed include: The d em o pr oced ur es abov e, P1 an d P2 , used t his par am et er . Had t h ose pr oced ur es ex plicit ly creat ed t heir pipes w it h t he CREATE_PI PE p rocedu re, w hich requ max pip esize, View in g const r aint s inir tes h eadat a dict ion ar yt hen t her e w ould not be a n eed for m axp ipesize as an ar gu m en t t o SEND_ MESSAGE. Com plex r ule enf orcem en t The SEND_MESSAGE pr ocedu r e cop ies t he cont ent s of t he m essage buf fer int o a d esignat ed SQL p r ogr s eand langu age tf ee eat tuhat res t he m essag e has b een read. A successfu l pipe. PL/ Upon com pletam ion ,unt hiter is no gu aran r et ur n code in dicat es only t hat t he message w as copied. Af t er t he call, t he local messag e pes bu ff erDat is aemt ypt y . and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch RECEIVE_MESSAGE m or e FUNCTION receive_message( Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce pipe_name IN VARCHAR2, for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly timeout IN INTEGER DEFAULT maxwait) RETURN INTEGER; int ellig en t , com plex dat abases. maxwait [ Team LiB ] constant integer := 86400000; RETURN INTEGER values: 0 - Success

/* 1000 days */

1 –LiB Timeout [ Team ] 2 – Record in pipe is too large for the buffer. 3 - Interrupted.

pipename This p aram et er is t he nam e of t he p ipe t h at is t h e sou r ce of t he m essage t o be r eceived. I n p rev iou s discussion s, t his w as r eferr ed t o as t he hom e p ipe. Pipe nam es ar e limit ed t o 1 28 char act er s. Do not use pipe n am es b eg inning w it h ORA$ as t hese ar e r eser v ed by Or acle. An opt ional arg um ent is t he t im e allow ed f or m oving t h e pipe con t en t s t o t he bu ff er . I f t he pipe is em pt y y ou w ill w ait on a m essag e unt il t he t im er exp ir es. You can p ost a r ead on j ust one pip e. This is in con t rast t o aler t s ( DBMS_ ALERT pack age) w her e y ou can post a " w ait on an y" aler t . I f a pr ocess w ishes t o r eceive dat a f r om sev eral pipes, t hat pr ocess m u st pole each p ipe w it h a • Table ofVE_ Content s RECEI MESSAGE. For t his r eason , t her e is no adv ant ag e t o a desig n in w hich Pr ogr am m ing a Orp a cl e ® Tr i gger s and Stor P roce dure s, Thir d Edi ti on r ocess has sever al he dome pipes. timeout

By Kevin Owens

You can u se a t im eou t of zer o t o issue a non blocking r ead. lish er:VE_MESSAGE Prent ice Hall PTR f un ct ion copies m essages fr om t he pip e int o t he local bu ff er . A ThePub RECEI successful indicat ed w it h a zer o ret u rn code. I f no messages ar e pr esent in t he pip e, Pub Dat e:read Decemisber 0 5, 2 003 y ou st ill g et 0-a13zer o, 33 ind I SBN: -0 850 -0icat ing a su ccessf ul r ead. Once y ou issue RECEI VE_ MESSAGE, y ou t hen un pack44t8he m essag e fr om t h e local buf fer int o local v ariab les. Pages:

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d UNPACK_MESSAGE t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. PROCEDURE unpack_message(item OUT VARCHAR22); Using easy- tunpack_message(item o- follow inst r uct ions an dOUT ex am ples, t his book pr esent s t echniq ues t o t ake PROCEDURE NUMBER); adv ant ag e of Or acle feat ur es such as t rig gers PROCEDURE unpack_messge(item OUT DATE);and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: ItemView This a v ariable hatt hhas been declar in is g const r aint st in e dat a dict ion ared y in y our p rocedur e. plexPE r ule enf orcem enides t The DCom BMS_PI packag e pr ov over loaded p r ocedu res f or un packing d if fer ent d at at y pes. You can p ack RAW an d LONG dat at y pes. The m od el for r eceiv in g dat a is t o issu e one p r ed ogrbam it s and langu agecom f eatm u res RECEIPL/ VESQL follow y aun series of UNPACK ands. Dat a t y pes and comp osit eurster ucopies ct u re t he n ex t message f rom you r buf fer int o t h e The UNPACK_ MESSAGE pr oced v ariab le. Th is is an OUT m ode v ar iab le. Follow ing t he call t o UNPACK, t hat v ariab le con t ains Er tr en or than and ions How do y ou k now w hat , if any t h in g, is in t he buf fer , t he con s ofdling t he lat estexcept message. esp ecially because a RECEI VE_ MESSAGE r et ur ns a successf ul ret ur n code w hen t he p ipe is I nt er - pr ocess com mu nicat ions emp t y ? The fun ct ion NEXT_ I TEM_TYPE is t h e key . I f you r code n eeds t o loop over m essag es in t he b uff er, you w ant t o in cor por at e NEXT_I TEM_ TYPE in y our loop. This is illust r at ed in t he Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch follow ing sam ple code. m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. RESET_BUFFER [ Team LiB ] PROCEDURE reset_buffer;

The RESET_ [ Team LiB ]BUFFER pr ocedu r e init ializes b uff er posit ion v ar iables declar ed wit h in t h e pack age b ody of DBMS_ PI PE. When a m essag e is sen t w it h SEND_ MESSAGE, t hese same v ariab les ar e init ialized as a m et hod of clear ing, and reset t ing, t he int er nal b uf fer. You wou ld call t his p rocedur e if a buf fer w as p ack ed an d you w ant ed t o clear it an d repack it wit h dif fer en t m essages, pr ior t o sen ding t he b uf fer m essages t o a pip e.

PURGE PROCEDURE purge(pipename IN VARCHAR2);



Table of Content s

pipename The n am e of t he p ip e y ou ar e cleaning out .

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

The PURGE p rocedu re r em oves an y m essages in t he pip e. This pr oced ur e fr ees all m em or y associat ed wit h t h e pipe. Pr ocesses t hat sen d an d r eceiv e m essages can abor t . Wh en t his occu r s, and t he p rocesses ar e r est ar t ed, t hey may see m essages left in t he pip e fr om t h e Pub lish er: Prent ice Hall PTR pr eviou s r un. I f t h is scenar io is p ossible, t he log ic of t hese pr ocesses sh ould be able t o det ect , Pub e: Decem ber ce 0 5,of 2 003 t hr ou ghDatt he p resen messag es in t h e pipe, a w arm st art sit uat ion, as opposed t o a cold I SBN: 013 -0 850 33 -0 st ar t . Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t NEXT_ITEM_TYPE Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. FUNCTION next_item_type RETURN INTEGER; Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake RETURN values: adv ant ag e of INTEGER Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he – evolv No more itemscov inerthe pipe. bu sin0ess es. Topics ed include: 9 – The next item in the buffer is a VARCHAR2 2 – The next item is a NUMBER. in g const s inis t h ea dat a dict ion ar y 3View – The nextr aint item DATE. Com plex r ule enf orcem en t The NEXT_I TEM_ TYPE f un ct ion pr ov ides t he ab ilit y t o " p eek " int o t he m essag e bu ffer . I t is SQL messag p r ogr am s and u ressent . Even if you k now wh at t y pe of usefu PL/ l w hen es un of itvar iouslangu t yp esage ar ef eat b eing m essage is b ein g sent , t his fu nct ion can be in cor p orat ed int o a WHI LE LOOP so you can br eak a t ytpes and comp osit e st u ct pt u re easilyDat w hen he messag e bu ff er isr em y. hanuse dling I f youErdroornot t h isand funexcept ct ion tions o det ect an em p t y buf fer , t h en y ou risk callin g UNPACK_MESSAGE on an em pt y bu ff er —t h is w ill generat e an ORA- 06 556 or an ORA- 065 59 I nt er - pr ocess com mu nicat ions err or . Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly UNIQUE_SESSION_NAME int ellig en t , com plex dat abases. FUNCTION RETURN VARCHAR2; [ Team LiBunique_session_name ] The UNI QUE_SESSI ON_ NAME fun ct ion r et ur ns a nam e like ORA$PI PE$ f ollow ed by a seq uence of let t er s an d d igit s. This p ip e nam e is pr ov ided by Or acle and is gu aran t eed t o be

un iq ue tLiB h rou [ Team ] ghou t all session s t hat con nect t o t hat inst ance. A p rocess mu st k now t he nam e of a p ipe pr ior t o calling SEND _MESSAGE; t he sam e holds t ru e for t he f unct ion, RECEI VE_ MESSAGE. When UNI QUE_SESSI ON_NAME is used t o gener at e pipe nam es, t here has t o be som e cent r al p ip e nam e r egist rat ion in t he f or m of a d at abase t able w h er e app licat ions regist er t heir pip e nam es; t hen ev er y pr ocess can kn ow t he hom e pipe n am e of all ot h er pr ocesses.

CREATE_PIPE, REMOVE_PIPE

Cr eat ion an d rem ov al of a p ip e can b e accom plished w it h t h e follow ing t w o f un ct ion s. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

FUNCTION create_pipe( pipename IN Hall VARCHAR2, Pub lish er: Prent ice PTR maxpipesize DEFAULT 8192, Pub Dat e: Decem ber IN 0 5, 2INTEGER 003 private IN BOOLEAN DEFAULT TRUE) RETURN INTEGER; I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

FUNCTION remove_pipe (pipename IN VARCHAR2) RETURN INTEGER;

Ou r ex am ples use t h e fu nct ions SEND _MESSAGE an d RECEI VE_MESSAGE t o im plicit ly cr eat e fect ively These creat e fun an d man plex datnam abases h Or acle! st ems dat abex ase per t tEf he pipes. ct ion s age creatcom e t he pipe ed inw itt he call if itSy does notand already ist .exYou Kevin ens plorees SQL, Or acle's answ er ove t o t hite w Stitrhuct ur ed QueryPE. Langu age ( SQL) , an d can imOw plicit ly ex creat a PL/ fu nct ion an d y et st ill r em REMOVE_PI t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake 11.20.3 Handling adv ant ag eException of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he The in g list t h e possib leed ex cep t ions t h at can occu r. The last it em in t his list , bu sinf ollow ess evolv es.s Topics cov er include: UNPACK_MESSAGE, is t h e m ost com mon , and w e w ill dem onst r at e PL/ SQL cod e t o h andle t his con dit ion. View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t inat ion pipe m ay r em ain f ull. When t his h appens, y ou w ill SEND_ MESSAGE: The dest w ait f or TI MEOUT seconds t o p ass an d t hen g et a ret ur n code of 1. PL/ SQL p r ogr am un it s and langu age f eat u res RECEI VE_ MESSAGE: I f t h e m essage in t he pipe is t oo larg e for t he b uff er , you get a a nt ycode pes and e st risu ct u re rDat et ur of 2.comp Th isosit ev ent not lik ely becau se all messages orig in at e f rom t he sam e size buf fer , w hich is lim it ed t o 4 096. The p ip e limit is t w ice t hat . Er r or han dling and except ions PACK_ MESSAGE: You can ov er flow you r local buf fer , w hich pr oduces an ORA- 0 655 8 Ierr nt er or -. pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim arYou y k ey , u un nique, eign k ey, eckbu , and UNPACK_MESSAGE, NEXT_ I TEM_TYPE: can packf or and emp t y ych our ff er , mwuch h ich m or e pr odu ces an ORA- 065 56 or an ORA- 0 655 9 er r or. Pr m ing Oracle igger and St or ed Pr ocedON_I ur es NI , Th Ed it ion is an inv aluable esou rce I n ogr PL/am SQL code, y ou Tr can uses PRAGMA EXCEPTI T tirod ensur e t,hat , should a p artr icular for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain ORA err or occur , y ou cap t ur e t h at as an except ion. This is how w e capt ur e an Or acle ert rruly or . int ellig en t , com plex dat abases. We ar e m ost concer ned w it h an er r or w hen w e un pack an em pt y message. I f no m essag e has [been Team LiBt o] ou r pipe, t he RECEI VE_ MESSAGE r et ur ns a st at us of 0. The f ollow ing er ror is sent gener at ed w h en w e f ollow t hat receiv e w it h eit h er a call t o UNPACK_ MESSAGE or NEXT_ I TEM_TYPE

[ Team LiB ]

ORA-06556: the pipe is empty, cannot fulfill the unpack_message request

The f ollow in g p r ocedu re, P3 , is m or e rob ust b ecause it w ill not fail. The p ar sing of m essage par t s is em bedd ed w it hin a loop—t his per m it s us t o get all message par t s. Th at code is fu r t her emb ed ded wit h in an except ion han dler . All of t his logic is em bedded w it hin a loop—b ut one t hat loops t hr ee t im es. Pr ocedu re P3, show n nex t , illust rat es h ow a PL/ SQL pr oced ur e can ser ve as an en dless- loop messag e han dler .



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

CREATE OR REPLACE procedure P3 By Kevin Owens is status integer; message_part varchar2(2000); Pub lish er: Prent ice Hall PTR message varchar2(2000); Pub Dat e: Decem ber 0 5, 2 003 exception; empty_buffer I SBN: 0- 13 -0 850 33 -0 pragma exception_init(empty_buffer, -6556); beginPages: 44 8 for i in 1..3 loop status := dbms_pipe.receive_message('HOME_OF_P3', 5); Ef fect ivelybegin creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t while Kevin Ow ens ex plor es(dbms_pipe.next_item_type PL/ SQL, Or acle's answ er t o t h e=St9) r uctloop ur ed Query Langu age ( SQL) , an d t eaches you w hat y dbms_pipe.unpack_message(message_part); ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. message := message||'-'||message_part; Using easy- t o- end followloop; inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag eexception of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our whenporempty_buffer thenw hich null; dat ab ases t o incor at e bu siness r ules ar e easy t o man age and m odif y as t he end;es. Topics cov er ed include: bu sin ess evolv end loop; dbms_output.put_line(message); View in g const r aint s in t h e dat a dict ion ar y end P3; Com plex r ule enf orcem en t Pr ocedu r e P4 is demon st rat ed w it h t he f ollow ing SQL* Plus session, w hich sends m essag es t o PL/ SQL ogr amP3 uncom it s and f eat u res t he pipe of P3p. r When pletlangu es t hrage ee cycles, t he out put is t he con cat enat ion of w hat ev er m essages w ere read. For t he SQL* Plus session w e hav e ( st ar t P3 bef ore t his session) : Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions SQL> Declar set feedback at iv e constoff r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch SQL> mvariable status number or e SQL> execute dbms_pipe.reset_buffer; SQL> execute dbms_pipe.pack_message('This is, Th message 1'); Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es ir d Ed it ion , is an inv aluable r esou rce SQL> is message for datexecute abase d evdbms_pipe.pack_message('This elopers, d esign er s, and pr oj ect leader s look in g 2'); t o b uild an d m aint ain t r uly SQL> :status := dbms_pipe.send_message('HOME_OF_P3'); int elligexecute en t , com plex dat abases. [ Team LiB ] The ou t pu t f rom P3 is t he f ollow ing .

[ Team LiB ] SQL> SET SERVEROUTPUT ON SQL> execute p3 -This is message 1-This is message 2 SQL>

[ Team LiB ]



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.21 Signaling Events with Alerts (DBMS_ALERT) The Oracle DBMS_ALERT p ack age allow s a pr ocess t o post a m essage t o anot h er pr ocess and hav e t h at m essage deliv ered only af t er a com m it . This is dif fer en t f r om pipes w her e a p r ocess post s a m essage an d t h at m essag e w ill alway s b e sent t o t he p ip e, regar d less of comm it or r ollb ack . Pipe m essag es ar e sent imm ediat ely. Aler t s ar e deliver ed on ly aft er t h e com m it . A pr ocess can post m any aler t s. None can be r eceiv ed un t il t he send in g pr ocess has done a comm it . Aler t s are asy nchr onou s. The sender can send an aler t sig nal w h et h er or not a r eceiv er h as a ThisofisContent also t rsue w it h pip es. Receiv er s can p ost a r ead- w ait wit h a t imer or t hey •post ed read.Table Pr ogream ing Or ® Tr s and e d P roce dure s,s Thir d Edi on e w it h t h e aler t buf fer issu am r ead ana cl d eret uri gger n . Sen derStor s and r eceiver comm u tinicat independ en t of each ot her. Sen ders never w ait on r eceiv er s, or v ice ver sa. By Kevin Owens Aler t s are f or p rocesses connect ed t o t he sam e inst an ce. Th e follow ing is one scen ario. Pub lish er: Prent ice Hall PTR

An applicat ion pr ogr am , APP_A, w r it t en in Jav a an d ru nning on ser v er host 01 .d omain .com , is Pub Dat e: Decem ber 0 5, 2 003 connect ed t o a d at abase on host db .d om ain . com t hr ough JD BC. A second applicat ion, APP_ B, 13 -0 33 -0 on host 02 . dom ain . com —t h is is con nect ed t o t he sam e dat ab ase on w r it t enI SBN: in C,0-is r u850 nning 8 com w it h ODBC. Ap plicat ion APP_A can p ost aler t s usin g t he DBMS_ALERT host dbPages: . dom44 ain. pack age. App licat ion APP_B, r un ning on a separ at e ser v er, can r eceive t hose aler t s—t h e int er m ed iar y is t h e dat ab ase. Th is scenar io is essent ially ap plicat ion - t o- applicat ion com mu nicat ion , even t hou gh t hese applicat ions r un on sep arat e m ach in es. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Aler t s Ow canens also fires edPL/ f rom t r igOrgers. Thansw at is er a pr nchrLangu onous age com(m un icat Kevin exbe plor SQL, acle's t oact t h eical St rfor uctmurof edasy Query SQL) , anion d because y ou wcan s aler b ut shrob ould ansact iondat fail, t he aler ar e bnev er t eaches you hatpost y ou num n eederou t o kn ow tt s, o build ust t he an dt rcom plex ab ases f or t ys our usiness. deliver ed . This is n ot so wit h p ip es. Messages post ed t o a pipe f r om w it hin a dat abase t r ig ger w ill alw ays bt oe deliver ed . rThis b ehan avior elpples, s w hen decidin h et hsert echniq t o u seues a pipe or an aler t . Using easyfollow inst uct ions d exham t his book gprwesent t o t ake Iadv f you t ex t as s of and comm nicatprion anur d est h atf eat com ion is ynot antar ageesending of Or acle feat uraesgener suchalasmtean rig gers st uored oced u rm esunicat t hat allow our tdat iedab t oases a t ran ion, hen use a p ipr ules e. I f w it 'hich s t r ansact ion tbased use and an aler t . y as t he t o sact incor por tat e bu siness ar e easy o man, age m odif bu sin ess evolv es. Topics cov er ed include: Pipes ar e also m or e su it ed f or lar ger t ext m essages. Aler t s ar e m odeled af t er t he UNI X SI GNAL par adigm , w h ich is int end ed t o just sig nal an event . One pr ocess sen ds a sig nal t o anot hView er prin ocess, and t he mer of tion h atarsignal, in t h is case aler t n ame, ind icat es t h e t y pe g const r aint s in t hee nam dat ae dict y of event t hat t ook p lace. Com plex r ule enf orcem en t The f ollow in g su mm ar izes t he d if fer en ces b et ween aler t s and p ip es. PL/ SQL p r ogr am un it s and langu age f eat u res Useap tipes ex comp changosit in get ex Dat y pesfor and st rtuual ct uinfor re m at ion becau se you can pass VARCHAR2, NUMBER, and DATE t yp es, an d t he b uff er for t ran sm ission is 4K. Er r or han dling and except ions Use aler t s t o sig nal an event . The aler t nam e is t he ind icat or of t he par t icular ev en t t h at nt er -ppr ocess com mu nicat ions tI ook lace. Declar iv elim const aint s,t ual including rim ar y You k ey ,can u nique, eign k ey, eck act , and Aler t s at are it ed rin t ex t r ansmpission. only df or eliv er 1, 800chchar ersmofuch t ex t . m or ealer t n ame is w hat id en t ifies t he ev en t . The Pr ogr A ammmessag ing Oracle Tr igger and is Stalw or ed oced ur ed es ., When Th ir d Ed it ion , isan analer invtaluable rce , e post ed t o a spipe ayPr s deliver y ou p ost , y ou arreesou saying for dat abaset hdeevreceiv elopers, d esign and ifprand oj ectw hen leader s lookitin. g " allow er t o get t heriss,only I comm " t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. Aler t s and pipes can wor k t og et her. Tw o pr ocesses can p ost m essages t o pipes bu t u se aler t s [ Team LiB ] or t hat w or k n eeds t o be done. For exam p le, a w ork er - pr ocess m ay spend m ost as an indicat of it s pr ocessing t im e idle, w ait ing t o r eceiv e any on e of sev er al aler t sign als. W hen t hat pr ocess r eceiv es an aler t , t h at par t icular aler t ind icat es a sp ecific t ask . Based on t h at t ask , t he wor k er- p r ocess w ill read m essages f rom one of sev er al pipes.

Messag [ Team es LiBsit] t ing in pipes an d aler t s, w ait in g t o b e deliv ered, ar e t em p orar y . I f t he d at abase goes d own , t he aler t s an d p ip e m essages w ill not be p resent w h en t h e dat abase com es up. The Oracle Adv anced Queuing op t ion p rov ides a rob ust f or m of queuin g m essag es t hat are int egr at ed in t o t he dat ab ase. Queues ar e imp lem ent ed w it h t ab les, so q ueues ar e r est or ed du rin g cr ash r ecover y. I f y ou put a messag e in a qu eu e and t he dat abase g oes d ow n b ef or e t he queue m essag e is deliver ed , t he queue m essag e w ill be pr esen t w hen t he d at abase com es b ack up. The API t o queues is ex t ensiv e, com par ed t o pipes and alert s. The pip es an d alert s are st r aigh t for w ar d f or ms of com m un icat ion, but a m essag e or alert can p ot ent ially be lost if t he dat abase cr ash es befor e a m essag e can b e r eceived. Pipe com m unicat ion requ ires no syn ch ron izat ion b et ween a sen der and r eceiv er . A PL/ SQL pr oced ur e can send a messag e t o a pip e at an y t im e. W het her a r eceiv er pr oced ur e r ead s fr om t hat pipe h as no ef fect on t he send er . Th er e is a m ild syn ch r onizat ion requ ir ed w it h alert s. A r eceiver m ust fir st r eg ist er f or an aler t . A r eceiver can r eg ist er f or m any alert s, but som eon e mu st r egist er f ir st . When t he alert is sent t he pr ocess t hat r egist ered w ill be ab le t o get t he alert Table . Once an alert is sen t , it is t oo lat e t o r eg ist er an d r eceiv e. The r egist er mu st • of Content s occu r fir st . I f y ou send an aler t and no pr ocess has r egist ered for t hat aler t , n o pr ocess w ill Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on ever b e able t o receiv e it . By Kevin Owens

" Ev ent " and " Signal" ar e ex cellent sy non ym s f or an alert . I f w e w an t t o k now t h at an event t ook p lace, w e only n eed t o be t old once. " The ligh t is on " —t hat is an ev ent , or an aler t . I f 10 Pub lish er: tPrent iceht HallisPTR people say h e lig on, t h e m essage is t he sam e as if said once. A p r ocess can send t he Pub Dat e: Decem ber 5, 2en 003t h ree t im es. When a r eceivin g p rocess issues a read, Or acle w ill sam e aler t t w ice, or0ev deliver I SBN: a sin0-gle aler t he r eceiv er only needs t o be t old once t h at t h at ev en t h as 13 -0 850t33because -0 occu r red. Messages, up t o 1, 800 char act er s, can accom pan y an aler t . Wh en m ult iple aler t s Pages: 44 8 w it h t he sam e nam e ar e issu ed an d t h er e is on e deliver y, t he m essage w it h t h e last sen t aler t is t he message deliver ed. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d 11.21.1 Interface Description t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. The f ollow in g p ar agr aphs d escr ibe t he DBMS_ALERT packag e API . Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: SIGNAL View in g const r aint s in t h e dat a dict ion ar y PROCEDURE signal( Com plex r ule enf orcem en t name IN VARCHAR2, message PL/ SQL p IN r ogrVARCHAR2); am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re han dling except nameEr r or The n am eand of t he alerions t . Aler t nam es ar e best if t hey ind icat e t he par t icular ev en t t hey signal, su ch as LOW_I NVENTORY. Alert nam es ar e limit ed t o 3 0 ch aract er s. I nt er - pr ocess com mu nicat ions message This is sup plement al t ext t o t he alert . The lim it is 1 ,8 00 char act er s. You can on ly Declarsen at ivd eaconst r aint s, including p rimt ar ey , u nique, f or eign k ey, ch eck VARCHAR2 as addit ional exty. kYou cann ot send a NUMBER or ,Dand ATEm t yuch pe m or e v ariab le. Th is pr oced ur e is not over loaded wit h ot h er t yp es. Pr ogrpam m ing eOracle igger St orsom ed Preoced ur pr es ocess , Th ir dhas Ed p it rion is an rinv esou This rocedur sendsTran alerst .and Unless ot h er ev ,iously eg aluable ist er ed fror an rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly alert , t his call is m eaningless. Some pr ocesses m ust fir st r egist er for an alert —t hen a sen der int ellig en t , com plex dat abases. can send t hat alert . [The Team ] alerLiB t n ame is t he k ey comp onent —t h is indicat es t he ev en t t h at n eeds t o be t ran smit t ed. You m ay find t h at y ou rar ely use t h e m essage par am et er , or use it f or supp lem ent al inf orm at ion only . Sup pose y ou h ave a m anuf act ur ing syst em . I n t h is syst em , inv en t or y is m oved fr om a st ock w arehou se t o an assem bly f loor —t h is is a f ully aut om at ed syst em . The

m ovem ent [ Team LiB of ] mat er ials inv olv es a D ELETE t rig ger on a dat abase inv en t ory t able. When it em s ar e delet ed , t he t rigg er ev aluat es h ow m uch in vent ory is left . I f in ven- t ory is t oo low , r esult in g f r om t he delet e, t h e t r ig ger sen ds a LOW_ I NVENTORY aler t t o anot her ORD ER I NVENTORY app licat ion. Th at aler t n ame sh ould be suf ficient inf orm at ion as t o w hat need s t o be d one. The addit ional 1, 800 char act ers can be su pplement al inf orm at ion t hat specif ies t he specif ics of ex act ly w hat m at er ials are sh ort .

REGISTER PROCEDURE register(name in VARCHAR2); •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

name The n am e of t he aler t . Aler t nam es need t o be sy nchr onized. Because all pr ocessed w it h aler t s mu st be conn ect ed t o t he sam e dat abase inst an ce, t h e off icial list of aler t nam es can be st or ed in a dat abase t ab le.

By Kevin Owens com mu nicat ion

Pub lish er: Prent ice Hall PTR

The g en er al behav ior of a r eceiver is t o r eg ist er f or one or m ore aler t s and t h en w ait on an y Pub Dat e: Decem ber 0 5, 2 003 of t hose aler t s. Let 's con t inue w it h t he man uf act u rin g ex am ple. There are a v ariet y of cr it ical SBN: 0- 13 -0 850 -0in g en vir onm ent . You can hav e an applicat ion t hat rem ains in an id le event s I in a m anuf act33ur 44 8for a pr oblem t o solv e ( e. g. , pr oblem s such as low inv en t or y and out - of - st ock st at e, Pages: w ait ing it ems) . This app licat ion w ould begin b y r eg ist er ing for bot h ev ent s an d t hen p ost in g a r eadw ait on eit her of t hese event s. Th is PL/ SQL code w ou ld b eg in w it h t he follow in g. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. dbms_alert.register('LOW_INVENTORY'); Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dbms_alert.register('OUT_OF_STOCK_ITEM'); dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: dbms_alert.waitany(name, message, status); View in g const r aint s in t h e dat a dict ion ar y This ap plicat ion w ould " sit " on t h e WAI TANY call unt il an aler t w as r eceiv ed. Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re WAITANY Er r or han dling and except ions PROCEDURE waitany( I nt er -OUT pr ocess com mu nicat ions name VARCHAR2, message OUT VARCHAR2, Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch status OUT INTEGER, m or e timeout IN INTEGER DEFAULT maxwait); Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce maxwait 86400000; /* s1000 for dat abase d constant ev elopers, integer d esign er s,:=and pr oj ect leader look indays g t o b*/ uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ] name This is an OUT mod e par am et er . Th e fir st or der of bu sin ess f or a p rocedur e t hat uses WAI TANY is t o det erm ine t he v alue of t his v ar iable. This v ar iable w ill con t ain one of t he alert nam es for w hich t h e pr ocess is r egist er ed. message This is an OUT mod e par am et er u sed if t he aler t sender w ishes t o d eliv er supp lem ent al t ex t . Th is is lim it ed t o 1 ,8 00 char act er s. status

0 is success. St at us = 1 wh en t h e t im er ex pir ed. So if t im eout is 10 and y ou r et ur n w it h a st at us of 1, t hen no aler t s w er e t here t o r eceive and t he 1 0- sec t im er ex pir ed.

timeout This is a r ead - w ait t im er in secon ds. This h as a d ef ault of 1, 000 d ays. This p rocedur e is v er y usef ul. I t m ean s t hat a single p r ocess can r egist er for m u lt ip le ev ent s and t h en w ait , w it h a single call, on t he occur r ence of any ev en t . When t he ev en t occur s ( i. e., ed) , t h e spr ocess p er for m s som e w or k, t hen g oes back and issu es an ot her •t he aler t is receiv Table of Content w ait Pr ogr.am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

A p r ocess cannot r est r ict a W AI TANY t o a su bset of t h e aler t s f or w hich t hat pr ocess is r eg ist er ed. I f a p rocess r eg ist er s for a LOW_I NVENTORY, OUT_OF_STOCK_I TEM, an d ot her alert s, t hen a WAI TANY w ill alw ays, an d can only , w ait on t h at f ull set of alert s. Pub lish er: Prent ice Hall PTR

Decem ber 0w5,it2hin 003 a t r ansact ion t hat is uncom m it t ed do not block subsequent aler t s AlerPub t s tDat hate: are sent I SBN: 013 -0 850 33 -0 t hat ar e sen t in comm it t ed t r ansact ion s. Assum e w e h ave a pr ocess t hat wait s on LOW_IPages: NVENTORY and OUT_OF_STOCK_I TEM. Anot her p rocess sen ds t he aler t , 44 8 LOW_I NVENTORY, but has n ot d one a com m it . Seconds lat er an ot her pr ocess sends t he aler t OUT_OF_STOCK_I TEM w it h an im m ed iat e comm it . Th e pr ocess w it h t he WAI TANY call w ill r eceive t he OUT_OF_ STOCK_I TEM im mediat ely .

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake WAITONE adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he PROCEDURE waitone( bu sin ess evolv es. Topics cov er ed include: name IN VARCHAR2, message OUT VARCHAR2, status View in g OUT constINTEGER, r aint s in t h e dat a dict ion ar y timeout IN INTEGER DEFAULT maxwait); Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res name This is t he nam e of t h e aler t for w h ich y ou w ish t o w ait . Th e ot her p aram et ers are Dat a t yical pes t and e stpr r uocedu ct u re re descr ibed ear lier . ident o t hecomp WAIosit TANY Er r or han dling and except ions I f an applicat ion is r egist er ed for sev er al aler t s, it m ak es sense t o post a WAI TANY. The WAI TONE ur e is for post ing I nt er -pr proced ocess com mu nicat ionsa r ead f or a sp ecific aler t . I f y ou r egist er for j ust one alert , t his p r ocedu re can be used t o w ait on t hat specif ic. Th e choice bet w een WAI TONE and WAI TANY isat a ivdesig n issue and d ep en dsp rim on how aler t s fuor pon oueck w ,ant ost Declar e const r aint s, including ar y kman ey , uy nique, eignw hich k ey, ych andt omp uch concur enet r ead- w ait s. mror Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] REMOVE PROCEDURE remove(name IN VARCHAR2);

Or acle docum [ Team LiB ] ent at ion r ecom m en ds t hat a pr ocedu re rem ov e an aler t t hat alert . An ap plicat ion p rog ram m ay be designed t o alw ay s hav e a m or e aler t s. I n t his case, t hat applicat ion is n ev er " f in ish ed " w it h any This is q uit e accep t able. A p rocedur e can r em ov e all r egist er ed aler t s pr oced ur e.

w h en it n o long er need s post ed r ead on on e or of it s r egist ered aler t s. w it h t he REMOVEALL

REMOVEALL PROCEDURE removeall;

An applicat ion can r emov e all aler t s for w hich it is regist er ed w it h t his one call. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

SET_DEFAULTS Pub lish er: Prent ice

Hall PTR

Pub Dat e: Decem ber 0 5, 2 003

PROCEDURE set_defaults(sensitivity IN NUMBER); I SBN: 013 -0 850 33 -0 Pages: 44 8

This p rocedur e set s a pollin g " sleep t im e" v alue t h at is u sed int er nally w it h calls t o WAI TANY. I t is n ot n ecessar y t o use t his p rocedur e u nless y ou w ant t o ov err ide t he def ault sleep per iod, w hich is fiv e sec. Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin ens [ TeamOw LiB ] ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

11.22 Email Notification with Triggers and Alerts Dat ab ase t rig gers can int er face w it h dat ab ase p ipes and aler t s. Figur e 11 - 16 illust r at es a m odel in w hich a dat ab ase t rigg er post s a not ificat ion t hat a pr of essor 's salar y has chan ged. This is a t r igger t h at f ires only f r om an upd at e of t he row . The t r igger p ost s t he aler t . When t he t ran sact ion com mit s, t h e sig nal is r eceiv ed b y a secon d Oracle d at abase connect ion. This connect ion is repr esent ed in Figur e 11 - 16 as PROCESS_ALERTS, w hich has on e pur pose, t o deliver em ail.

Figu r e 1 1 -1 6 . Tr igge r Em a il N ot if icat ion. •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Becau se PROCESS_ALERTS r un s asyn ch ron ously, it has no im pact on ot her dat ab ase act iv it y. Updat e t ran sact ions t o t h e PROFESSORS t ab le do n ot w ait for an em ail t o b e sen t . Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens plor es inPL/ SQL, answ er ser t o vice t h e St r uct ur ed est Query age ( SQL) an d We st ar t w it h ex dev elop g an in t Or er facle's ace t hat will email requ s. ThLangu is in t erf ace w ill ,be tused eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. by PROCESS_ALERTS. I t w ill accept st andar d email p ar amet er s: sen der, receiv er, subj ect , and t ext . This int er face is a packag e and has t he f ollow ing specif icat ion : Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: CREATE OR REPLACE PACKAGE email_pkg IS View in g const r aint s in t h e dat a dict ion ar y PROCEDURE send (p_sender IN VARCHAR2, p_recipient IN VARCHAR2, Com plex r ule enf orcem en t p_message IN VARCHAR2, p_subject IN VARCHAR2); END email_pkg; PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re The n ex t st ep is t o develop an en gine t h at w ill dedicat e it self t o ser v icin g sign als. Th is can b e Figur eions 11 - 16 sh ows PROCESS_ALERTS as a st and- alon e pr oced ur e. a st anErd-r alone rocedur or hanpdling ande.except At t his poin t w e need t o consider using a sing le pr oced ur e, and a p ack age could be a bet t er choice. I nt er - pr ocess com mu nicat ions We n eed Declar a patrocedur iv e const e troaint r eceive s, including aler t s and p rimaarpry ocedu k ey , urenique, t o send f or eign aler t s. k ey, Thechsend eck , ing andoccur m uch s in t he t rig ger. m or e I t seem s r eason able t o define a pack age specif icat ion t o su ppor t t he send and r eceive fun ct ion s. That packag e sp ecif icat ion is show n next . Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ] CREATE OR REPLACE PACKAGE alerts_pkg IS PROCEDURE process_alerts; PROCEDURE send_alert(message IN VARCHAR2);

END alerts_pkg; [ Team LiB ] Figur e 11 - 16 is redr aw n t o show t he m odif ied ar chit ect u re. I n Figur e 11 - 17, t h e t r igger calls t he SEND_ALERT pr oced ur e t o p ost t he aler t . Th e code used t o r eceive t he aler t is in t he sam e packag e.

Figu r e 1 1 -1 7 . Re vi se d Tr i gge r Em a il Not if icat i on.



Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 The assum pt ion is t h at t h e t r igger w ill use t h e pr ofessor ' s nam e t o const ru ct an email addr ess Pages: 44 8ad dr ess t o t he pr ocedu re in t h e ALERTS_PKG packag e. I deally , t h e and pass t h at PROFESSORS t able w ould hav e a colum n t hat cont ains em ail add resses.

The d at abase t r igger is set u p t o send an em ail only w h en t h er e is a diff er ence in t he old and new Ef fectsalar ivelyy.creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our CREATE ORt oREPLACE TRIGGER professors_aur dat ab ases incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he AFTER UPDATE ONTopics professors bu sin ess evolv es. cov er ed include: FOR EACH ROW WHEN (OLD.SALARY NEW.SALARY) BEGINView in g const r aint s in t h e dat a dict ion ar y alerts_pkg.send_alert(:new.prof_name||'@domain.com'); END; Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res For t his m od el, all in t er f aces h ave b een show n. W e can st ar t look ing at t he bod y for t he Dat a pack t y pes and The compemail osit e body st r u ctisu re indiv idual ages. sh own h er e. This b ody includes g lob al declarat ion s for t he SMTP serv er I P ad dr ess an d p ort nu mb er . This is t he mechanism b y w hich t h e pack age Er r or han dling and except ions ALERTS_PKG w ill deliv er em ail for each aler t r eceiv ed. The body of ALERTS_ PKG w ill include a call Itnt o er t he ail SEND prnicat ocedur e. - prem ocess com mu ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce CREATE OR REPLACE PACKAGE email_pkg IS s look in g t o b uild an d m aint ain t r uly for dat abase d ev elopers, d esignBODY er s, and pr oj ect leader g_smtp_server CONSTANT VARCHAR2(20) := '00.00.00.00'; int ellig en t , com plex dat abases. g_smtp_server_port CONSTANT PLS_INTEGER := 25; [ Team LiB ] PROCEDURE send (p_sender IN VARCHAR2, p_recipient IN VARCHAR2, p_message IN VARCHAR2, p_subject IN VARCHAR2)

IS LiB ] [ Team mail_conn utl_smtp.connection; BEGIN mail_conn := utl_smtp.open_connection (g_smtp_server, g_smtp_server_port); utl_smtp.helo (mail_conn, g_smtp_server); utl_smtp.mail (mail_conn, p_sender); utl_smtp.rcpt (mail_conn, p_recipient); utl_smtp.open_data(mail_conn); utl_smtp.write_data (mail_conn,'From: "'||p_sender ||'" '||utl_tcp.CRLF); utl_smtp.write_data (mail_conn,'To: "'||p_recipient • Table of Content s ||'" '||utl_tcp.CRLF); Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on utl_smtp.write_data By Kevin Owens (mail_conn, 'Subject: ' ||p_subject||utl_tcp.CRLF); utl_smtp.write_data Pub lish er: Prent ice Hall PTR (mail_conn, utl_tcp.CRLF||p_message); Pub Dat e: Decem ber 0 5, 2 003 utl_smtp.close_data(mail_conn); I SBN: utl_smtp.quit 0- 13 -0 850 33 -0 (mail_conn); END send; Pages: 44 8 END email_pkg;

The p ackag e body f or t h e sen ding and r eceiving of alert s is show n next . The subp r ogr am t o Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t r eceive aler t s is coded t o w ait for t h r ee aler t s; each w ait in clu des a 1 0- sec t imer . The loop Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d also t er min at es wh en it receiv es an aler t message of " END ." The aler t d ev ice nam e is t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. " em ail_ not ificat ion. " Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake For an anachr onous applicat ion, a separ at e pr ocess t hat r uns in t h e back gr ound w ill inv oke adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our PROCESS_ALERTS. Locally , PROCESS_ ALERTS can b e r un fr om SQL* Plus. As cod ed her e, it dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he w ill deliver t h e fir st t h ree em ails t hat result fr om up dat es t o t he PROFESSORS t able. bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t CREATE OR REPLACE PACKAGE BODY alerts_pkg IS PROCEDURE process_alerts PL/ SQL p r ogr am un it s and langu age f eat u res IS Dat aprofessor_email t y pes and comp ositVARCHAR2(100); e st r u ct u re status INTEGER; Er r or han dling and except ions BEGIN dbms_alert.register('email_notification'); I nt er - pr ocess com mu nicat ions FOR I IN 1..3 LOOP Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e dbms_alert.waitone Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly (name => 'email_notification', int ellig en t , com plex dat abases. message => professor_email, status => status, [ Team LiB ] timeout => 10); IF status = 0 THEN EXIT WHEN professor_email = 'END';

[ Team LiB ]

email_pkg.send (p_sender=>'[email protected]', p_recipient=>professor_email, p_subject=>'Salary', p_message=>'Salary has changed'); END IF; END LOOP; END process_alerts;

PROCEDURE send_alert(message IN VARCHAR2) IS BEGIN dbms_alert.signal('email_notification', message); END send_alert; END alerts_pkg; •

Table of Content s

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on

[ Team LiB ]

By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]

[ Team LiB ]

Brought to You by



Table of Content s

Like the book? Buy it!

Pr ogr am m ing Or a cl e ® Tr i gger s and Stor e d P roce dure s, Thir d Edi ti on By Kevin Owens

Pub lish er: Prent ice Hall PTR Pub Dat e: Decem ber 0 5, 2 003 I SBN: 0- 13 -0 850 33 -0 Pages: 44 8

Ef fect ively creat e an d man age com plex dat abases w it h Or acle! Sy st ems and dat ab ase ex per t Kevin Ow ens ex plor es PL/ SQL, Or acle's answ er t o t h e St r uct ur ed Query Langu age ( SQL) , an d t eaches you w hat y ou n eed t o kn ow t o build rob ust an d com plex dat ab ases f or y our b usiness. Using easy- t o- follow inst r uct ions an d ex am ples, t his book pr esent s t echniq ues t o t ake adv ant ag e of Or acle feat ur es such as t rig gers and st ored pr oced ur es- f eat u r es t hat allow y our dat ab ases t o incor por at e bu siness r ules w hich ar e easy t o man age and m odif y as t he bu sin ess evolv es. Topics cov er ed include: View in g const r aint s in t h e dat a dict ion ar y Com plex r ule enf orcem en t PL/ SQL p r ogr am un it s and langu age f eat u res Dat a t y pes and comp osit e st r u ct u re Er r or han dling and except ions I nt er - pr ocess com mu nicat ions Declar at iv e const r aint s, including p rim ar y k ey , u nique, f or eign k ey, ch eck , and m uch m or e Pr ogr am m ing Oracle Tr igger s and St or ed Pr oced ur es , Th ir d Ed it ion , is an inv aluable r esou rce for dat abase d ev elopers, d esign er s, and pr oj ect leader s look in g t o b uild an d m aint ain t r uly int ellig en t , com plex dat abases. [ Team LiB ]