Unit 12 (Program Units 1)
Unit 12 (Program Units 1)
ALCHEMY SOLUTIONS
Objectives
At the end of this unit you will be able to: List the advantages of building PL/SQL subprograms. Create & !e"ute PL/SQL fun"tions. Call a stored fun"tion from within SQL. Create & !e"ute #atabase $riggers.
Topics
%ntrodu"tion PL/SQL Pro"edure PL/SQL &un"tion Pa"'ages #atabase $riggers
ALCHEMY SOLUTIONS
Intro !ction
(ra"le allows a""essing and manipulating database information using pro"edural s"hema ob)e"ts "alled PL/SQL program units. Pro"edures* fun"tions* and pa"'ages are all e!amples of PL/SQL program units. A pro"edure or a fun"tion is a s"hema ob)e"t that logi"ally groups a set of SQL and other PL/SQL programming language statements together to perform a spe"ifi" tas'. Pro"edures and fun"tions are "reated in a user+s s"hema and stored in a database for "ontinued use. ,ou "an e!e"ute a pro"edure or fun"tion intera"tively using an ora"le tool* su"h as SQL Plus or in (ra"le &orms or in the "ode of another pro"edure or trigger. Pro"edures and fun"tions are nearly identi"al. $he only differen"es are: &un"tions always return a single value to the "aller. Pro"edures return one or more than one values to the "aller. Pro"edures provide advantages in the following areas: Se"urity Performan"e .emory allo"ation Produ"tivity %ntegrity Sec!rit" Stored pro"edures "an help enfor"e data se"urity. ,ou "an restri"t the database operations that users "an perform by allowing them to a""ess data only through pro"edures and fun"tions. Per#or$%nce Stored pro"edures "an improve database performan"e. /se of pro"edures dramati"ally redu"es the amount of information that must be sent over a networ' "ompared to issuing individual SQL statements or sending the te!t of an entire PL/SQL blo"' to ora"le. &urthermore be"ause a pro"edure+s "ompiled form is readily available in the database no "ompilation step is re0uired to e!e"ute the "ode. Additionally if the pro"edure is already
ALCHEMY SOLUTIONS
present in the shared pool of the S1A retrieval from dis' is not re0uired and e!e"ution "an begin immediately. Me$or" %&&oc%tion 2e"ause stored pro"edures ta'e advantage of the shared memory "apabilities of (ra"le only a single "opy of the pro"edure needs to be loaded into memory for e!e"ution by multiple users. Sharing the same "ode among many users results in a substantial redu"tion in (ra"le memory re0uirements for appli"ations. Pro !ctivit" Stored pro"edures in"rease development produ"tivity. 2y designing appli"ations around a "ommon set of pro"edures* you "an avoid redundant "oding and in"rease your produ"tivity. Inte'rit" Stored pro"edures improve the integrity and "onsisten"y of your appli"ations. 2y developing all your appli"ations around a "ommon group of pro"edures you "an redu"e the li'elihood of "ommitting "oding errors.
Anon"$o!s PL/SQL (&oc)s vs* Store Proce !res Sending an unnamed PL/SQL blo"' to (ra"le server from an (ra"le tool or an appli"ation "reates an anonymous PL/SQL blo"'. (ra"le "ompiles the PL/SQL blo"' and pla"es the "ompiled version in the shared pool of the S1A but does not store the sour"e "ode or "ompiled version in the database for subse0uent reuse. Shared SQL area allows a "ompiled anonymous PL/SQL blo"' already in the shared pool to be reused and shared until it is flushed out of the shared pool. Alternatively a stored pro"edure is "reated and stored in the database as an ob)e"t. (n"e "reated and "ompiled it is a named ob)e"t that "an be e!e"uted without re"ompiling. Additionally dependen"y information is stored in the data di"tionary to guarantee the validity of ea"h stored pro"edure. %n summary by moving PL/SQL blo"'s out of a database appli"ation and into stored pro"edures you avoid unne"essary pro"edure re"ompilations by (ra"le at runtime improving the overall performan"e of the appli"ation and (ra"le.
ALCHEMY SOLUTIONS
BEGIN
EXCEPTI N
END
$ransfer values to and from the "alling environment through arguments. a"h argument in the pro"edure will have one of the three modes. %n mode is default. Ar'!$ent IN OUT +escription Pass a value from the "alling environment into the pro"edure 3default4 5eturn a value from the pro"edure to the "alling environment.
Pass a value from the "alling environment into the pro"edure* return a potentially different value from the pro"edure to the "alling environment.
Cre%te % PL/SQL proce !re St%te$ent S"nt%, CREATE PROCE+URE C$EATE % $ $EP&ACE' P$ CED($E )rocedure*name (argument1 %mode1' datat+)e1, argument2 %mode2' datat+)e2, -.) I/ 0 A/ Pl123l*4loc56 -.ere REPLACE proce !re/n%$e %r'!$ent $o e is spe"ified when pro"edure already e!ists. is the name of the pro"edure is the name of a PL/SQL variable passed to the pro"edure denotes the type of argument %6 3default4 (/$ %6 (/$ is the datatype of the argument is the pro"edural blo"' that defines the a"tion performed by the pro"edure.
/se the 'eyboard AS instead of %S* if desired7 they are e0uivalent. Start the sub8program blo"' with the 'eyword 2 1%6 or with a lo"al variable de"laration. 6ever start the sub8program blo"'s with the 'eyword # CLA5 .
ALCHEMY SOLUTIONS
nd the blo"' with the 'eyboard 6#* or 6# followed by the pro"edure name.
Invo)e t.e Proce !re $o environments. S"nt%, Procedure*name (argument1, argument2,--)6 invo'e the pro"edure "reated from various
-.ere
is the name of the pro"edure. is the variable* e!pression* "onstant* or literal passed to the pro"edure.
Note $he number and datatypes of the a"tual arguments spe"ified when the pro"edure is invo'ed must mat"h the number and datatypes of the formal arguments spe"ified when the pro"edure was "reated. $he names of the arguments do not have to mat"h. /se 9 C/$ "ommand to invo'e pro"edure from SQLPlus.
Pass values from the "alling environment into the pro"edure using %6 argument. E,%$p&e PL/SQL Co e /pdate the salary of the spe"ified employee to the spe"ified amount C5 A$ (5 5 PLAC P5(C #/5 raise:salary 3v:empno %6 emp.empno;$,P * v:newsal %6 emp.sal ;$,P 4 %S
7
/P#A$ emp S $ sal < sal = v:newsal >? 5 empno < v:empno7 C(..%$ >(5@7 6# raise:salary7
/ SQLA 9 C/$ raise:salary 3BCDE*CFF47 5eturn values from the pro"edure to the "alling environment into using (/$ arguments.
E,%$p&e PL/SQL
5etrieve the salary of the spe"ified employee. C5 A$ (5 5 PLAC P5(C #/5 get:sal 3v:empno %6 emp.empno;$,P * v:sal (/$ emp.sal ;$,P 4 %S 2 1%6 S L C$ sal %6$( v:sal &5(. emp >? 5 empno < v:empno7 6# get:sal7 / SQLA GA5%A2L g:sal number SQLA 9 C/$ get:sal 3BCDE*: g:sal47 SQLAP5%6$ g:sal
Pass values from the "alling environment into the pro"edure and 5eturn potentially different values from the pro"edure to the "alling environment using %6 (/$ arguments. E,%$p&e position. Add a dash to the spe"ified phone number at the "orre"t
ALCHEMY SOLUTIONS
v:phone :< S/2S$5 3v:phone* E*H4 II J8J II S/2S$5 3v:phone* K*K47 6# add:dash7
PL/SQL 1!nction
Create a PL/SQL fun"tion instead of a pro"edure when invo'ing the subprogram as part of an e!pression* rather than as a "omplete statement.
Procedure
Call!ng En"!ronment IN Argument (Declare)
BEGIN
EXCEPTI N
9 END
ALCHEMY SOLUTIONS
Create a fun"tion to return a value to the "alling environment. St%te$ent S"nt%, CREATE 1UNCTION
C$EATE % $ $EP&ACE' ;(NCTI N <unct!on*name
(argument1 %mode1' datat+)e1, argument2 %mode2' datat+)e2, -) $ET($N datat+)e I/ 0 A/ )l123l*4loc56 -.ere REPLACE #!nction/n%$e %r'!$ent $o e %t%t"pe RETURN fun"tion. p&/s0&/b&oc) Note /se the 'eyword AS instead of %S* if desired7 they are e0uivalent. A return statement ./S$ e!ist within the PL/SQL blo"'. is spe"ified when pro"edure already e!ists. is the name of the fun"tion is the name of a PL/SQL variable passed to the fun"tion denotes the %6 of argument is the datatype of the argument denotes the argument outputted by the is the pro"edural blo"' that defines the a"tion performed by the fun"tion.
Invo)e t.e 1!nction $o invo'e the fun"tion within a PL/SQL e!pression. S"nt%, ut)ut*"ar!a4le= > <unct!on*name (argument1, argument2-.)6
1:
ALCHEMY SOLUTIONS
-.ere o!tp!t/v%ri%b&e value #!nction/n%$e %r'!$ent is the output variable for storing the returned by the fun"tion. is the name of the fun"tion is the variable* e!pression* "onstant* or literal passed to the fun"tion.
E,%$p&e PL/SQL Co e
5etrieve the salary of the spe"ified employee C5 A$ (5 5 PLAC &/6C$%(6 get:salary 3v:empno %6 emp.empno;$,P 4 5 $/56 6/.2 5 %S G:sal emp.sal;$,P 7 2 1%6 S L C$ sal %6$( v:sal &5(. emp >? 5 empno < v:empno7 5 $/56 3v:sal47 6# get:salary7 / SQLAGA5%A2L g:salary 6/.2 5 2 1%6 6#7 / SQLAP5%6$ g:salary : g:salary :< get:salary 3BCDE47
E,%$p&e is PL/SQL Co e
Create a fun"tion that returns an employee+s bonus whi"h 2ased on their salary and department to whi"h they belong C5 A$ (5 5 PLAC &/6C$%(6 get:bonus 3v:empno %6 emp.empno; $,P 4 5 $/56 6/.2 5 %S 2on emp."omm;$,P 7
11
ALCHEMY SOLUTIONS
PL/SQL PROGRAM UNITS G:deptno emp.deptno;$,P 7 G:)ob emp.)ob;$,P 7 G: sal emp.sal;$,P 7 S L C$ deptno* )ob* sal %6$(v:deptno* v:)ob* and v:sal &5(. emp >? 5 empno < %& v:deptno <EF $? 6 %& v:)ob 6($ %6 3JCL 5@+*+SAL S.A6+4 $? 6 bon: < v:sal- F.K7 LS 2on: <v:sal - F.C7 6# %&7 LS 2on: < v:sal - F.D7 6# %&7 5 $/56 3bon47 6#7 / SQLAGA5%A2L ! 6/.2 5 2 1%6 : 9: < get:bonus 3BCDE47 6#7 / SQLAP5%6$ !
2 1%6
v:empno7
E,%$p&e
5etrieve the employee+s name* salary* "ommission an bonus /sing the fun"tion "reated. S L C$ ename* sal* "omm* get:bonus 3empno4 2(6/S &5(. emp >? 5 deptno < DF7 ENAME S.%$? SAL COMM CFFF SC($$ HFFF CFFF HFFF (ONUS EFFF NFF
&(5#
12
ALCHEMY SOLUTIONS
P%c)%'es
A pa"'age is a group of related pro"edures and fun"tions* together with "ursors and variables they use* stored together in the database for "ontinued use as a unit. Similar to standalone pro"edures and fun"tions* pa"'aged pro"edures and fun"tions "an be "alled e!pli"itly by appli"ations or users. Pa"'ages offer several development and performan"e Advantages over standalone pro"edures. Stored pro"edures not defined within the "onte!t of a pa"'age are "alled standalone pro"edures. Pro"edures defined within a pa"'age are "onsidered a part of the pa"'age. Pa"'ages are used to define related pro"edures* variables* and "ursors. Pa"'ages are often implemented to provide advantages in these areas: n"apsulation of related pro"edures and variables. Separation of the pa"'age spe"ifi"ation and pa"'age body. #e"laration of publi" and private pro"edures* variables* "onstants* and "ursors. #efinition of persistent pa"'age variables. 2etter performan"e. Enc%ps!&%tion Stored pa"'ages allow you to en"apsulate* or group* related stored pro"edures* variables* datatypes* et" in a single named* stored unit in the database. $his provides for better organiPation during the development pro"ess. n"apsulation of pro"edural "onstru"ts in a pa"'age also ma'es privilege management easier. 1ranting the privilege to use a pa"'age ma'es all "onstru"ts of the pa"'age a""essible to the grantee. $he methods of pa"'age definition allow you to spe"ify whi"h variables* "ursors* and pro"edures are: P!b&ic Priv%te #ire"tly a""essible to the user of a pa"'age. ?idden from the user of a pa"'age.
&or e!ample pa"'age might "ontain ten pro"edures. ?owever* the pa"'age "an be defined so that only three pro"edures are publi" and therefore available for e!e"ution by a user of the pa"'age 7 the
13
ALCHEMY SOLUTIONS
remainder of the pro"edures are private and "an be only a""essed by the pro"edures within the pa"'age.
Sep%r%te P%c)%'e Speci#ic%tion %n P%c)%'e (o " A pa"'age is "reated in two parts: the spe"ifi"ation and the body pa"'age+s spe"ifi"ation de"lares all publi" "onstru"ts of the pa"'age and the body defines all "onstru"ts 3publi" and private4 of the pa"'age. Per#or$%nce I$prove$ent /sing pa"'ages rather than standalone pro"edure results in the following improvements: $he entire pa"'age is loaded into memory when a pro"edure within the pa"'age is "alled for the first time. $his load is "ompleted in one operation* as opposed to separate loads re0uired with standalone pro"edures. $herefore* when "alls to related pa"'aged pro"edures o""ur* no dis' %/( is ne"essary to e!e"ute the "ompiled "ode already in memory. A pa"'age body "an be repla"ed and re"ompiled without affe"ting the spe"ifi"ation. >hen you "reate a pro"edure or pa"'age* ora"le automati"ally performs these steps: Compiles the pro"edure or pa"'age. Stores the "ompiled data. Stores the pro"edure or pa"'age in the database. >hen a standalone or pa"'aged pro"edure is invo'ed* ora"le performs these steps to e!e"ute it: Gerifies user a""ess. Gerifies pro"edure validity. !e"utes the pro"edure.
14
ALCHEMY SOLUTIONS
Package Specification
#e"lare publi" "onstru"ts within the pa"'age spe"ifi"ation. S"nt%, C$EATE $ $EP&ACE PAC?AGE )ac5age*name I/ @ar!a4le declarat!on Cur2or declarat!on EAce)t!on declarat!on Procedure declarat!on ;unct!on declarat!on END )ac5age*name6
Where P%c)%'e/n%$e is the name of the pa"'age pro"edure 2%ri%b&e ec&%r%tion de"lare variables or "onstants. C!rsor ec&%r%tion de"lare e!pli"it "ursor. E,ception de"lare e!"eption. ec&%r%tion Proce !re de"lare pro"edure interfa"e ec&%r%tion 1!nction ec&%r%tion de"lare fun"tion interfa"e
15
ALCHEMY SOLUTIONS
Package body
#e"lare all "onstru"ts 3publi" and private4 within the pa"'age body. S"nt%, C$EATE $ $EP&ACE PAC?AGE B DB )ac5age*name I/ @ar!a4le declarat!on Cur2or declarat!on EAce)t!on declarat!on Procedure declarat!on ;unct!on declarat!on END )ac5age*name6
Where
P%c)%'e/n%$e name of the pa"'age pro"edure. 2%ri%b&e ec&%r%tion de"lare variables or "onstants. C!rsor ec&%r%tion de"lare e!pli"it "ursor. e,ception ec&%r%tion de"lare e!"eption. Proce !re ec&%r%tion de"lare pro"edure interfa"e* 1!nction ec&%r%tion de"lare fun"tion interfa"e. $he spe"ifi"ations hold publi" de"larations* whi"h are visible to the appli"ation and "an be thought* as an operational interfa"e. $he body holds implementation details and private de"larations* whi"h are hidden to the appli"ations and "an be thought as a Jbla"' body+. A pa"'age "an be repla"ed* enhan"ed or repla"ed without "hanging the interfa"e to the pa"'age body.
1#
ALCHEMY SOLUTIONS
(nly the de"larations in the pa"'age spe"ifi"ation are visible and a""essible to appli"ations. %mplementation details in the pa"'age body are hidden and ina""essible. So* the body "an be "hanged without having to re"ompile "alling programs. $o referen"e the types* ob)e"ts and subprograms de"lared within a pa"'age spe"ifi"ation* use the dot notation as follows: pa"'age:name.type:name pa"'age:name.ob)e"t:name pa"'age:name.subprogram:name Pa"'age "ontents from database triggers* stored subprograms* embedded PL/SQL blo"'s and anonymous PL/SQL blo"'s sent to ora"le intera"tively by SQL - Plus or SQL - #2A "an be referen"ed. Calling Packaged Subprograms A pa"'aged subprogram "an be "alled from a database trigger* another stored subprogram* or an ora"le tool su"h as SQL - Plus. Pa"'aged subprograms must be referen"ed using dot notation as shown below: mp:a"tion.hire:employee 3name* titleQ.47 $his tells PL/SQL "ompiler that hire:employee is found in the pa"'age emp:a"tions. Note &un"tion get:bonus* pro"edure get:sal and add:dash are Publi" pro"edures that are visible to "alling environment Pro"edure return:error is a private pro"edure that is not visible to the "alling environment* while it "an be a""essed by all the pro"edures and fun"tions de"lared as part of the Pa"'age body. E,%$p&e C5 A$ (5 5 PLAC PAC@A1 emp:trans AS &/6C$%(6 get:bonus 3v:empno %6 6/.2 54 5 $/56 6/.2 57 P5(C #/5 get:sal3v:empno %6 6/.2 5* v:sal (/$ 6/.2 547 P5(C #/5 add:dash 3v:phone %6 (/$ GA5C?A5 D47 6# emp:trans7 C5 A$ (5 5 PLAC PAC@A1 2(#, emp:trans AS errnum 6/.2 53C4 7 errmess GA5C?A5D3CF47
17
ALCHEMY SOLUTIONS
8888888888888885 $/56: 55(58888888888888888 P5(C #/5 return:error3errnum %6 6/.2 5* errmess %6 GA5C?A5D4 %S 2 1%6 %6S 5$ %6$( temp 3message4 GAL/ S 3$(:C?A5 3errnum II J:+ II errmess47 6#7 888888888888881 $:SAL88888888888888888888888888 P5(C #/5 get:sal 3v:empno %6 6/.2 5* v:sal (/$ 6/.2 54 %S 2 1%6 S L C$ sal %6$( v:sal &5(. emp >? 5 empno < v:empno7 9C P$%(6 >? 6 6(:#A$A:&(/6# $? 6 rrnum: <SQL"ode7 5eturn:error 3errnum*+5e0uired data not found+47 >? 6 ($? 5S $? 6 rrnum: <SQL"ode 5eturn:error 3errnum*+Standard rror+47 6#7 88888888888881 $:2(6/S8888888888888888 &/6C$%(6 get:bonus 3v:empno %6 6/.2 54 5 $/56 6/.2 5 %S 2onus emp."omm;$,P 7 v:deptno emp.deptno;$,P 7 v:)ob emp.)ob;$,P 7 v:sal emp.sal;$,P 7 2 1%6 S L C$ deptno* )ob* sal %6$( v:deptno* v:)ob* v:sal &5(. emp >? 5 empno <v:empno7 %& v:deptno < EF $? 6 %& v:)ob 6($ %6 3JCL 5@+*+SAL S.A6+4 $? 6 2onus: <v:sal-F.K7 LS 2onus: <v:sal-F.C7 6# %&7
18
ALCHEMY SOLUTIONS LS
2onus: <v:sal-F.D 6# %&7 5 $/56 3bonus47 9C P$%(6 >? 6 6(:#A$A:&(/6# $? 6 rrnum: <SQL"ode7 5eturn:error 3errnum*+5e0uired data not found+47 >? 6 ($? 5S $? 6 rrnum: <SQL"ode7 5eturn:error 3errnum*+Standard rror+47 6#7 8888888888888A##:#AS?88888888888888888 P5(C #/5 add:dash 3v:phone %6 (/$ GA5C?A5D4 %S 2 1%6 G:phone: <S/2S$5 3v:phone* E*H4II+8 JIIS/2S$5 3v:phone* K*K47 9C P$%(6 >? 6 6(:#A$A:&(/6# $? 6 rrnum: <SQL"ode7 5eturn:error 3errnum*+5e0uired data not found+47 6#7 6# emp:trans7
19
ALCHEMY SOLUTIONS
Database Triggers
A database trigger is a PL/SQL pro"edure asso"iated with a table. >henever a SQL statement is issued for a table that satisfies a trigger "ondition* ora"le automati"ally e!e"utes 3fires4 the trigger. $riggers are similar to stored pro"edures trigger "an in"lude SQL and PL/SQL statements to e!e"ute as a unit and invo'e other stored pro"edures. ?owever* pro"edures and triggers differ in a way that they are invo'ed. >hile a user or an appli"ation e!pli"itly e!e"utes a pro"edure* a trigger is impli"itly fired 3e!e"uted4 by ora"le when no matter what user is "onne"ted or what appli"ation is being used. $riggers are stored in the databases* desperately from their asso"iated tables. $riggers "an only be defined on tables* not on views. ?owever* triggers on the basetable3s4 of a view are fired if an %6S 5$* /P#A$ * (5 # L $ statement is issued against a view. /se of #atabase $riggers Note >hen a trigger is fired* SQL statement within its trigger a"tion potentially "an fire other triggers. >hen a statement in a trigger body "auses another trigger to be fired* the triggers are said to be "as"ading. $he e!"essive use of triggers "an result in "omple! interdependen"ies* whi"h may be diffi"ult to maintain large appli"ations. $o automati"ally generate derived "olumn values. $o prevent invalid transa"tions. $o enfor"e "omple! se"urity authoriPations. $o enfor"e referential integrity a"ross nodes in a distributed database. $o enfor"e "omple! business rules. $o provide transparent event logging. $o provide sophisti"ated auditing. $o maintain syn"hronous table repli"ates. $o gather statisti"s on table a""ess.
2:
ALCHEMY SOLUTIONS
(ra"le allows you to define pro"edures that are impli"itly e!e"uted when an %6S 5$* /P#A$ * or # L $ statement is issued against the asso"iated table. $hese pro"edures are "alled database triggers. $riggers and de"larative integrity "onstraints "an both be used to "onstrain data input. ?owever* triggers and integrity "onstraints have signifi"ant differen"es. A de"larative integrity "onstraint is a statement about the database that is always true. A "onstraint applies to e!isting data in the table and any statement that manipulates the table. $riggers "onstrain what transa"tions "an do. A trigger does not apply to data loaded before the definition of the trigger. $herefore* it does not guarantee all data in a table "onforms to the rules established by an asso"iated trigger. A trigger enfor"es transitional "onstraints7 tah is a trigger only enfor"es a "onstraint at the time that the data "hanges. $herefore* a trigger* not a de"larative integrity "onstraint* should enfor"e a "onstraint su"h as Mma'e sure that the delivery date is at least seven days from todayR.
+%t%b%se Tri''er Str!ct!re A database trigger has three basi" parts: A triggering event or statement. A trigger restri"tion. A trigger a"tion. Tri''erin' Event Or St%te$ent %t is an SQL statement that "auses a trigger to be fired. %t "an be an %6S 5$* an /P#A$ or a # L $ statement for a spe"ifi" table. A triggering statement "an also spe"ify multiple #.L statements. Tri''erin' Restriction
21
ALCHEMY SOLUTIONS
A trigger restri"tion spe"ifies 2oolean 3logi"al4 e!pression that must be $5/ for the trigger to fire. %t us an option available for triggers that are fired for ea"h row. %ts fun"tion is to "ontrol e!e"ution of the trigger. A trigger restri"tion is spe"ified using a >? 6 "lause. Tri''er Action A trigger a"tion is the pro"edure 3PL/SQL 2L(C@4 that "ontains the SQL statements and the PL/SQL "ode to be e!e"uted when a triggering statement is issued and the trigger restri"tion evaluates to $5/ . %t "an "ontain SQL and PL/SQL statements7 "an define PL/SQL language "onstru"ts and "an "all stored pro"edures. Additionally* for row triggers* the statements in a trigger a"tion have a""ess to "olumn values of the "urrent row being pro"essed. T"pes o# Tri''ers >hen you define a trigger* you "an spe"ify the number of times the trigger a"tion is to be e!e"uted. $he types of triggers are as e!plained below: Ro3 tri''ers A row trigger is fired ea"h time the table affe"ted by the triggering statement. &or e!ample: if an /P#A$ statement updates multiple rows of a table* a row trigger is fired on"e for ea"h row affe"ted by the /P#A$ statement. St%te$ent Tri''ers A statement trigger is fired on"e on behalf of the triggering statement* independent of the number rows the triggering statement affe"ts. (E1ORE 2s A#ter Tri''ers
>hen defining a trigger you "an spe"ify the trigger timing* i.e. you "an spe"ify when the triggering a"tion is to be e!e"uted in relation to the triggering statement. 2 &(5 and A&$ 5 apply to both row and statement triggers. 2 &(5 triggers e!e"ute the trigger a"tion before the triggering statement. $hese types of triggers are "ommonly used in the following situations: >hen the trigger a"tion should determine whether or not triggering statement should be allowed to be "ompleted. 2y using 2 &(5
22
ALCHEMY SOLUTIONS
trigger* you "an eliminate unne"essary pro"essing of the triggering statement. $o derive spe"ifi" "olumn values before "ompleting a triggering %6S 5$ or /P#A$ statement.
A&$ 5 trigger e!e"utes the trigger a"tion after the triggering statement is e!e"uted. $hese types of triggers are "ommonly used in the following situations. >hen you want triggering statement to "omplete before e!e"uting the trigger a"tion. %f a 2 &(5 trigger is already present* different a"tions on the same triggering statement "an be performed.
Co$bin%tions /sing "ombinations of the triggers e!plained so far* four types of triggers "ould be "reated. Before Statement Trigger 2efore e!e"uting the triggering statement* the trigger a"tion is e!e"uted. Before Row Trigger 2efore modifying ea"h row affe"ted by the triggering statement and before Appropriate integrity "onstraints* the trigger is e!e"uted* if the trigger restri"tion either evaluated to $5/ or was not in"luded. After Statement Trigger After e!e"uting the triggering statement and applying any deferred %ntegrity "onstraints* the trigger a"tion are e!e"uted. After Row Trigger After modifying ea"h row affe"ted by the triggering statement and Possibly applying appropriate integrity "onstraints* the trigger a"tion is e!e"uted for the "urrent row* if the trigger restri"tion either evaluates to $5/ or was not in"luded. /nli'e 2 &(5 row trigger* A&$ 5 row triggers have rows lo"'ed.
23
En%b&e An enabled trigger e!e"utes its trigger a"tion if a triggering statement is issued and the trigger restri"tion 3if any4 evaluates to $5/ . +is%b&e A disabled trigger e!e"utes its trigger a"tion if a triggering statement is issued and the trigger restri"tion 3if any4 would evaluate to $5/ . &or enabled triggers* ora"le automati"ally: !e"utes triggers in a planned firing se0uen"e when a single SQL statement fires more than one trigger. Performs integrity "onstraint "he"'ing at a set point in time with respe"t to the different types of triggers and guarantees that triggers "annot "ompromise integrity "onstraints. Provides read8"onsistent views for 0ueries and "onstraints. .anages the dependen"ies among the triggers and ob)e"ts referen"ed in the "ode of the trigger a"tion. /ses two8phase "ommit if a trigger updates remote tables.
Data Access for Triggers >hen a trigger is fired* the tables referen"ed in the trigger a"tion might be "urrently undergoing "hanges by SQL statements "ontained in other user+s transa"tions. %n all "ases* the SQL statements e!e"uted within triggers follow the "ommon rules used for stand8alone SQL statements. %f an un"ommitted transa"tion has modified values that a trigger being fired either needs to read 30uery4 or write 3update4* the SQL statements in the body of the trigger being fired use the following guidelines: Queries see the "urrent read8"onsistent snapshot of referen"ed tables and any data "hanged within the same transa"tion. /pdates wait for e!isting data lo"'s before pro"eeding.
!ecution of Triggers (ra"le internally e!e"utes a trigger using the same steps used for pro"edure e!e"ution* the only subtle differen"e is that user a""ess to fire a trigger is verified if a user has the privilege to e!e"ute a triggering statement. (ther than this* triggers are validated and e!e"uted the same way as stored pro"edures.
24
ALCHEMY SOLUTIONS
St%te$ent S"nt%,
CREATE TRIGGER C$EATE % $$EP&ACE' T$IGGE$ %u2ername.' Tr!ggername CBE; $E1A;TE$D CDE&ETE1IN/E$T1(PDATED % ; columnname %, columnname, columnname-.'' N %u2ername.' ta4lename %; $ EACE $ F %FEEN cond!t!on' $E;E$ENCING &D A/ oldname NEF A/ neGname' DEC&A$E @ar!a4le declarat!on2 Con2tant declarat!on2 BEGIN P&1/H& 2tatement2 END6
Where REPLACE
re"reates the trigger if it already e!ists. ,ou "an use this option to "hange the definition of an e!isting trigger without first dropping it. is the same the user* in whose wor' area the trigger >ill be stored. %f you omit the username* ora"le "reates the trigger in the wor'8area of the user who "reated the trigger.
Usern%$e
Tri''ern%$e is the name of the trigger to be "reated. (E1ORE A1TER +ELETE indi"ates that ora"le fires the trigger before !e"uting the triggering statement. indi"ates that ora"le fires the trigger after e!e"uting the triggering statement. indi"ates that ora"le fires the trigger whenever a # L $ statement removes a row from the table. $he (&
25
ALCHEMY SOLUTIONS
"olumnname S* "olumnname*QT option is not available for # L $ . INSERT indi"ates that ora"le fires the trigger whenever an %6S 5$ statement adds a row to the table. $he (& "olumnname S* "olumnname*QT option is not available for %6S 5$.
UP+ATE indi"ates that ora"le fires the trigger whenever an /P#A$ statement "hanges a value in one of the "olumns spe"ified in the (& "lause. %f the (& "olumnname S* "olumnname*QT "lause is spe"ified* ora"le fires a trigger whenever the /P#A$ statement "hanges a value of a "olumn spe"ified in this "lause* else it will be fired whenever the /P#A$ statement "hanges a value in any "olumn of the table. ON spe"ifies the username and the name of the table on whi"h the trigger is to be "reated. %f you omit the username* ora"le assumes the table is in your own wor'8area. ,ou "an "reate a trigger on a table in the wor'8area S,S. Spe"ifies "orrelation names. $he "orrelation names "an be used in the PL/SQL blo"' and in >? 6 "lause of a row trigger to refer spe"ifi"ally to old and new values of the "urrent row. $he default "orrelation names are (L# and 6 >.
RE1ERENCING
designates the trigger to be a row trigger. (ra"le fires a for ea"h row that is affe"ted by the triggering statement and meets the optional trigger "onstraint defined in the >? 6 "lause. %f you omit this "lause* the trigger is a statement trigger. spe"ifies the trigger restri"tion. $he trigger restri"tion "ontains an SQL "ondition that must be satisfied for ora"le to fire the trigger. $his "ondition must "ontain "orrelation names and "annot "ontain 0uery. (ra"le evaluates this "ondition for ea"h row affe"ted by the triggering statement. %s the PL/SQL blo"' that ora"le e!e"utes to fire the trigger $his blo"' "annot "ontain transa"tion SQL statements i* e C(..%$* 5(LL2AC@ and SAG P(%6$.
-HEN
+ECLARE* EN+
2#
ALCHEMY SOLUTIONS
Tri''ern%$e E,%$p&e
A trigger to "he"' the salary of the employees before insert or update on emp table and raise e!"eption whenever the salary of an employee goes out of range. $he minimum and ma!imum salary limit for ea"h designation is stored in the sal table. PL/SQL Co e
C5 A$ (5 5 PLAC $5%11 5 "he"':sal 2 &(5 %6S 5$ (5 /P#A$ (& sal* )ob (6 emp &(5 AC? 5(> >? 6 3new.)obUA+P5 S%# 6$+4 # CLA5 v:minsal sal.minsal;$,P 7 v:ma!sal sal.ma!sal;$,P 7 sal:out:of:range 9C P$%(67 2 1%6 S L C$ minsal* ma!sal %6$( v:minsal* v:ma!sal &5(. sal >? 5 )ob <: new.)ob7 %&: new.salUv:minsal (5: new.salAv:ma!sal $? 6 5A%S sal:out:of:range7 6# %&7 9C P$%(6 >? 6 sal:out:of:range $? 6 5A%S :APPL%CA$%(6 55(5 38DFEFF* +Salary out of range.+47 6#7 / A database trigger to automati"ally update Commission of employees who are salesman.
E,%$p&e
PL/SQL Co e C5 A$ (5 5 PLAC $5%11 5 derive:"omm 2 &(5 %6S 5$ (5 /P#A$ (& sal (6 emp
27
ALCHEMY SOLUTIONS
PL/SQL PROGRAM UNITS &(5 AC? 5(> >? 6 3new.)ob <+SAL S.A6+4 2 1%6 : new."omm: <: old."omm - 3: new.sal /: old.sal47 6#7 /
E,%$p&e
Create a trigger to ma'e sure that the in"rease in salary for employees in the emp table is only EF; of the previous salary.
PL/SQL Co e C5 A$ (5 5 PLAC $5%11 5 in":sal 2 &(5 /P#A$ (& sal (6 emp &(5 AC? 5(> 2 1%6 : 6ew.sal: < L AS$ 3: new.sal*:old.sal-E.E47 6#7 / E,%$p&e Create a trigger to "hange the department number in the emp table whenever "hanges o""ur in the department table.
PL/SQL Co e C5 A$ (5 5 PLAC $5%11 5 "as:up A&$ 5 /P#A$ (& deptno (6 dept &(5 AC? 5(> 2 1%6 /P#A$ emp S $ emp.deptno <: new.deptno7 >? 5 emp.deptno <: old.deptno7 6#7 / E,%$p&e SQL Co$$%n Res!&t E,%$p&e SQL Co$$%n /pdate when referential "onstraint is not present. SQLA/P#A$ # P$ S $ # P$6( <E >? 5 # P$6(<EF E row updated. Add referential "onstraint. SQLAAL$ 5 $A2L .P
28
ALCHEMY SOLUTIONS
PL/SQL PROGRAM UNITS D A## C(6S$5A%6$ .P:&(5 %16:@ , H &(5 %16 @ , 3# P$6(4 5 & 5 6C S # K P$ 3# P$6(47
$able altered. /pdate when referential "onstraint is present. SQLA/P#A$ # P$ D S $ # P$6(<D >? 5 # P$6(<E7 /P#A$ # P$ 4 55(5 at line E: (5A8FKFOE: table /S 5E.# P$ is mutating* trigger /fun"tion may not see it. (5A8FNCED: at line D. (5A8FKFLL7 error during e!e"ution of trigger+s 5E.CAS:/P+.
INSTEA+ O1 Tri''er %n (ra"le L INSTEA+ O1 $riggers were introdu"ed. %t is fired to do something else instead of performing the a"tion that e!e"uted the trigger. $hese triggers are "alled %6S$ A# (& triggers be"ause* unli'e other types of triggers* (ra"le fires the trigger instead of e!e"uting the triggering statement. $he %6S$ A# (& option "an only be used for triggers "reated over views. $he 2 &(5 and A&$ 5 options "annot be used for triggers "reated over views.
29
ALCHEMY SOLUTIONS
%6S$ A# (& triggers provide a transparent way of modifying views that "annot be modified dire"tly through /P#A$ * %6S 5$* and # L $ statements. E,%$p&e SQL Co e $o update the base table through a )oin view Create or 5epla"e Giew Voinview as Sele"t empno*ename*)ob*sal*emp.deptno*dname*lo" from emp* dept where emp.deptno<dept.deptno7
SQL Co e SQLA insert into )oinview values3EFFD*WaaaaW*OFFF*DF*WssssW*WeeeeW47 insert into )oinview values3EFFD*WaaaaW*OFFF*DF*WssssW*WeeeeW4 55(5 at line E: (5A8FEBBO: "annot modify a "olumn whi"h maps to a non 'ey8preserved table 6ow write normal /P#A$ * %6S 5$* and # L $ statements against the view* and the %6S$ A# (& trigger wor's invisibly in the ba"'ground to ma'e the right a"tions ta'e pla"e. PL/SQL Co e C5 A$ (5 5 PLAC $5%11 5 Vointrig %6S$ A# (& %6S 5$ (6 Voinview &(5 AC? 5(> 2 1%6 %6S 5$ %6$( #ept GAL/ S :new.dname*
:new.deptno*
6#7
/ 6ow if an %nsert statement is fired on view Voinview* then the values are inserted in the mp and #ept table.
SUMMARY 56
3:
ALCHEMY SOLUTIONS
$he PL/SQL programs "an be stored in the database as stored programs and "an be invo'ed whenever re0uired. $his avoids reparsing when multiple users invo'e it. PL/SQL has two types of subprograms "alled Pro"edures and &un"tions Subprograms allows to brea' a program down into manageable* well defined logi" modules A Pro"edure is a subprogram that performs a spe"ifi" a"tion. A pro"edure "an be "alled from any PL/SQL program or from SQL prompt. A &un"tion is a subprogram that retruns a value A fun"tion must have a 5 $/56 "lause. 5 $/56 statement is used to return the "ontrol to the "alling environment Act!%& P%r%$eters are the variables or e!pressions referen"ed in the parameter list of a subprogram 1or$%& P%r%$eters are the variables de"lared spe"ifi"ation and referen"ed in the subprogram body in a subprogram
$here are three argument modes whi"h "an be used with any subprograms %6 $he %6 parameter lets the user pass values to the "alled Subprogram. %nside the subprogram* the %6 parameter a"ts li'e a "onstant* therefore it "annot be modified. (/$ $he (/$ mode parameter lets the user return values to the "alling nvironment. %nside the subprogram* the (/$ parameter a"ts li'e an unintialised variable. $herefore* its value "annot be assigned to another variable or to itself. %6 (/$ $he %6 (/$ parameter lets the user pass intial values to the "alled Subprogram and returns updated values the "alling blo"'. Stored Pa"'age is a database ob)e"t that groups logi"allyrelated PL/SQL ob)e"ts. %t en"apsulate related pro"edures* fun"tions* asso"iated "ursors and variables together as a logi"al unit in the database
31
ALCHEMY SOLUTIONS
Pa"'ages are made of "omponents : $he spe"ifi"ations de"lares the types* e!"eptions* "ursors and subprograms variables* "onstants*
$he body defines "ursors and subprograms. %t holds imlementation details and private de"larations* whi"h are hidden from the appli"ation
Pa"'ages offer several advantages whi"h in"ludes modularity* easier appli"ation design* information hiding* added fun"tionality and better performan"e $o referen"e the types* ob)e"ts and subprograms de"lared within a pa"'age spe"ifi"ation* dot notation is used as follows : Pa"'age:name.type:name Pa"'age:name.ob)e"t:name Pa"'age:name.subprogram:name A #atabase $rigger is a stored PL/SQL program unit asso"iated with a database table. $he database triggers impli"itly gets fired whenever the affe"ted by any SQL operation A database trigger has three parts : A tri''erin' event is the SQL statement 3 %6S 5$* /P#A$ or # L $ statement for a spe"ifi" table4 that "auses a trigger to be used A tri''er restriction is spe"ified using a >? 6 "lause. A trigger restri"tion spe"ifies a 2oolean e!pression that must be $5/ to fire. $he trigger a"tion is not e!e"uted if the restri"tion evaluates to &ALS . A tri''er %ction is the pro"edure that "ontains the SQL statements and PL/SQL "ode to be e!e"uted when a triggering statement is issued and the trigger restri"tion evaluates to $5/
the the
$o "reate a database trigger there are three different options available to us : 2 &(5 option (ra"le fires the trigger only on"e* before e!e"uting A&$ 5 option $riggering statement (ra"le fires the trigger only on"e* after e!e"uting
32
ALCHEMY SOLUTIONS
triggering statement %6S$ A# (& option (ra"le fires the trigger only on"e* to do something else trigger $here are two levels at whi"h trigger "an be fired 5ow Level $rigger Statement Level $rigger instead of performing the a"tion that e!e"uted the
PL/SQL PROGRAMMING
LA( E7ERCISES
PL/SQL
E. Create a table mployee with the following rows and "olumns: Eno +eptn A ress P.one S%&%r" (on!s o E D EH* S2% Colony* CHCKNL CFFFF .adras D H DH* 5am Colony* NLNCKD EFFFF .adras H E ECBK* Anna BLCKNO LFFF 6agar* .adras K D HK* 6aidu Street* HKHCNH LFFF .adras C H EK* 5a)a 6agar* DCNKNH OCFF .adras D. #evelop a PL/SQL blo"' to do the following: Cal"ulate the value for the 2onus "olumn as F.KF - Salary. %f salary is greater than 5s. LFFF* then no bonus should be rewarded to the employee. Cal"ulate the value for the $otal "olumn as Salary = 2onus. Tot%&
33
H. >rite PL/SQL "ode do the following: &ind the average and the total of the salaries of all employees in department number H. &ind the highest and the lowest of the salaries of all employees and the differen"e between them. &ind the names* employees numbers and salaries of the five highest8 paid employees.
K. #evelop a PL/SQL blo"'* whi"h returns a number ea"h from two tables then inserts the sum of these numbers into a third table. $he pro"ess should terminate after all the rows are fet"hed from either of the two tables.
C. #evelop a PL/SQL blo"' to: /pdate the telephone number of an employee with employee number H to NDKFDHF. #elete the re"ord where the employee is e0ual to D. %nsert a new employee into the employee table. Commit the updates that are made to the data. N. #evelop a blo"' to store the number of employees belonging to departments whi"h number D toH. B. $ype the following "ommand at the SQL prompt: Create table 6umbers 36umber integer not null47 #evelop a blo"' that fills the table above with numbers E to EFF in"lusive using an %& loop. L. $ry to fill the above 6umbers table with numbers from E toEFF using a &(5 loop. O. &ill the 6umbers table with values from E to EFF using a >?%L loop. EF.5ewrite the previous statement using the 9%$ statement. EE.Create table Players with the following rows and "olumns:
34
ALCHEMY SOLUTIONS P&%"ern o N KK LH D DB N%$e .ahesh 2anu ?arish lango Chris Initi%&s 5 G G.P S 5.?
PL/SQL PROGRAM UNITS Street ldams 5oad 5' .utt 5oad 1andhi Street 6adu Street 5am 6agar Le%'!eno LKNB ENFL DKEE BLOL
ED.Create table $eams with the following rows and "olumns: Te%$no E D P&%"erno N DB +ivision &irst Se"ond
EH.Create a table with the following rows and "olumns: M%tc.no Te%$no P&%"erno -on E D H K C E E E E E N N N KK LH H D H H F
Lost E H F D H
EK.Create a table with penalties with the following rows and "olumns: Paymentno Playerno Pendate Amount E D H K C N B N KK DB EFK KK L DB FL8#e"8OF FC8#e"8OE EE8Sep8OD FL8#e"8OK FL8#e"8OF FL8#e"8OF ED86ov8OK EFF.FF BC.FF EFF.FF CF.FF DC.FF DC.FF BC.FF
35
ALCHEMY SOLUTIONS
EC.#evelop a PL/SQL blo"' that deletes all the re"ords from the Penalties table where the penalty amount is greater than 5s.CF. EN.#evelop a PL/SQL blo"' that does the following: Cal"ulate the average of the amount "olumn in the Penalties table and store the result in a variable "alled Javerage+. %n"rement the value of the variable Javerage+ by EF. Compare the Amount "olumn of the Penalties with the variable Javerage+ and delete all the re"ords from the Penalties table where the value in the Amount "olumn is greater than the value stored in the variable Javerage+.
EB.#evelop a PL/SQL blo"' that does the following: Cal"ulate the average of the Amount "olumn and store in a variable "alled Javerage+. %f Javerage+ is greater than EFF then update the Penalties table by multiplying the "olumn Amount by F.OC.
EL.>rite a PL/SQL blo"' to do the following: Cal"ulate the average of the Amount "olumn and store it in a variable Javerage+ %f average is less than EF then per"entage 3a user defined variable4 is e0ual to C* else if average is greater than EF* then per"entage is e0ual to F* else if average is greater than EFF* then per"entage is e0ual to XC. %n other "onditions the per"entage should be e0ual to E. /pdate table Penalties by setting the "olumn Amount as: Amount < Amount - 3E=3per"entage/EFF4.
EO.#evelop a blo"' that "he"'s whether ea"h player in the .at"hes table has a league number delete the player+s details from the .at"hes table. DF.$ry solving the above problem by using a Loop8 !it when8"ondition. DE.Solve the above problem by using a &or loop.
3#
ALCHEMY SOLUTIONS
DD./se a sub0uery in pla"e of the "ursor to a""omplish the same )ob. DH.#evelop a blo"' to store the numbers of the players born between EOCF and EONF in help table using a "ursor. DK.#evelop a blo"' to store the numbers of the players born between EOCF and EONF in help table using a "ursor but without using any (pen &et"h or Close statements. DC.#evelop a blo"' to delete all teams from the $eams table on the "ondition that five teams remain. DN.#evelop a blo"' to add a new team. %f the "aptain number does not o""ur in the Players table the update must be rolled ba"'. DB.#evelop a blo"'* whi"h rolls ba"' the transa"tion if 3by a""ident4 a division by Yero o""urs. DL.#evelop a blo"' to roll ba"' the transa"tion if too large a value is inserted into the "olumn. DO.#evelop a PL/SQL blo"' that stores the relevant te!t of all SQL C(# S in the table. >e assume the Code:table has been "reated with two "olumns. HF.Create a table Sales with the following rows and "olumns. Sno E D H K C N 6ame 5aman 1opal $arun 1ovind 5e'ha 5aa'hi Salary CFFF NCFF CFFF BFFF CCFF BCFF 6ativity .adras 2ombay Co"hin .adras 2ombay 2ombay $arget DFFFF HFFFF DFFFF ECFFF DFFFF DFFFF Sales EFLFF DFFFF LFFF CFFF ECFFF EBFFF #anapal A'ila A'ila .anage r #anapal Pro)e"t EFE EFH EFE EFD EFE EFH
#evelop a PL/SQL blo"' to do the following: /pdate the salary by 5s.ECFF for all employees whose "odes are greater than K and for the remaining employees by 5s.CFF.
37
ALCHEMY SOLUTIONS
List the employees whose sales are below NF; of the target. &ind all the employees whose native pla"es are either 2ombay or .adras.
HE.#evelop a PL/SQL blo"' to do the following: Assign the employee $arun together with his manager to pro)e"t number EFH. Assign the employees with employee number greater than H to pro)e"t number EFE. Assign all other employees to pro)e"t number EFD.
HD.Create a table "alled .essages with "olumns Serial6o and .essage. >rite PL/SQL "ode to insert numbers from E to C in the Serial6o "olumn and a "onstant te!t in the message "olumn.
HH. Create three "olumns "alled inventory* Cust:orders and Spe"ial:orders as follows: Inventor" S6umber3N4T Produ"t8id E D H C!st/or ers SChar3HF4T Produ"t8name Sugar 5i"e >heat SChar3DF4T Produ"t8status %n sto"' 2a"' ordered Spe"ial order S6umber3H4T Std8order80ty EFF DFF HFF
38
ALCHEMY SOLUTIONS S6umber3ED4T (rder8no E D H K C Speci%&/or ers S6umber3ED4T (rder8no S6umber3N4T Produ"t8id S6umber3N4T Produ"t8id E E H D D
S6umber3H4T (rder80ty
$ype an order number and get the "orresponding P5(#/C$:%#. Sear"h the %nventory table. %f the produ"t is M%6 S$(C@R pla"e a date into the order+s asso"iated A55%GAL:#A$ whi"h is seven days from today+s date S/se S,S#A$ = BT. %f the produ"t is M2AC@ (5# 5 #R* pla"e a date into the order+s asso"iated A55%GAL:#A$ whi"h is one month from today+s date. S/se A##:.(6$?S 3S,S#A$ = E4T %f the produ"t is MSP C%AL (5# 5R* pla"e a date from today+s date into the order+s asso"iated A55%GAL:#A$ S/se A##=.(6$?S 3S,S#A$ * D4T and fulfil the spe"ial order by inserting a row into the SP C%AL:(5# 5S table. /se the (5# 5:6( from the C/S$:(5# 5S table. /se the standard order 0uantity 3S$#:(5# 5:Q$,4 in the order.
39