Vous êtes sur la page 1sur 30

Chapter 13

CHAPTER 13 --------------------------------------------------------------------------------------------------------------------

PROCEDURES, FUNCTIONS, PACKAGES, AND TRIGGERS


This chapter covers the creation of named database objects that store executable code. Oracle subprograms include both procedures and functions. These are named PL/ !L bloc"s that can optionall# include one or more parameters. $hen called% a procedure performs a data processing action can return multiple values% &hile a function usuall# performs a calculation of some sort and returns a single value to the calling procedure. The chapter also covers Oracle pac"ages. Li"e procedures and functions% a pac"age belongs to a schema. ' pac"age groups PL/ !L t#pes% variables% exceptions% and subprograms that are logicall# related. Pac"ages ma"e it easier to develop applications b# providing a named PL/ !L module &ith simple% &ell(defined interfaces. The chapter also teaches #ou to program database triggers. Triggers are PL/ !L bloc"s that execute for predefined database events% such as the insertion of a ro& in a database table. Triggers are useful for activities such as the automation of data archiving and the enforcement of complex data integrit# rules. OBJECTIVES )n this chapter% #ou &ill learn the basic s"ills re*uired to+ Create and drop procedures , includes passing parameters and values. Create and drop functions , includes returning values. Create pac"age specifications% pac"age bodies% stored% pac"ages% cursor processing in pac"ages% and calling stored pac"ages. Create% alter% drop% enable% and disable triggers , includes before and after triggers.

PROCEDURES AND FUNCTIONS -oth procedures and functions are classified as Oracle subprograms. -oth procedures and functions can be programmed to perform a data processing tas". .unctions are t#picall# coded to perform some t#pe of calculation. -oth procedures and functions are named PL/ !L bloc"s% and both can be coded to ta"e parameters to generali/e the code. -oth can be &ritten &ith declarative% executable% and exception sections. The primar# difference is that procedures are called &ith PL/ !L statements &hile functions are called as part of an expression. )f this is not clear at this time% do not &orr# because the examples throughout this chapter &ill clarif# these t&o different t#pes of subprograms. )n previous chapters% #ou &or"ed &ith anon#mous PL/ !L bloc"s. 0o& #ou &ill learn to created named bloc"s that are stored as database objects. Procedures and functions are normall# stored in the database &ithin pac"age specifications , a pac"age is a sort of &rapper for a group of named bloc"s. Procedures and functions can also be stored as individual database objects. ' procedure or function is parsed and compiled at the time it is stored. 's a result%
1evised+ 11(23(45 13 ( 1

Chapter 13

these coded objects tend to execute faster &hen compared to nonprocedural !L scripts because nonprocedural scripts re*uire extra time for compilation. Procedures and functions can be invo"ed from most Oracle tools li"e !L6Plus% and from other programming languages li"e C77 and 8'9'. The benefits of creating these t#pes of stored database objects include+ )mproved data securit#. )mproved data integrit#. )mproved application performance. )mproved maintenance.

The use of named procedures and functions improves data securit# in t&o &a#s. This approach controls the access to base database objects such as the tables that store data. The creation of procedures and functions enables non(privileged application users to access data% but limits the access to that provided through the use of procedures and functions. :ata integrit# is improved b# ensuring that related actions on database tables are performed together% as a unit% b# funnelling actions for related tables through a single path of access and execution. This is termed transaction integrity , either all updates that comprise a transaction are executed or none of them are executed. 'pplication performance is improved in several &a#s. .irst% the abilit# to store procedures and functions as compiled objects avoids reparsing the objects for multiple users b# exploiting the capabilities of shared !L for an Oracle database. -ecause the PL/ !L has alread# been parsed and compiled% this avoids parsing at runtime. -undling the !L and PL/ !L statements into procedures and functions reduces the number of database calls made% thus reducing net&or" traffic. 'll statements in procedures and functions are passed to a database together as a single object. 'pplication maintenance is improved. Procedures and functions can be modified online &ithout interfering &ith the &or" of other developers and application users. ingle procedures and functions that perform common tas"s can be modified &ithout having to directl# &or" on multiple applications that ma# call these common procedures and functions. 'dditionall#% this approach eliminates duplicate testing that might other&ise ta"e place. PROCEDURES Procedures are simpl# named PL/ !L bloc"s. The# are created and o&ned b# a particular schema% usuall# the schema of the programmer developing the object. Li"e the commonl# used :;L functions such as CO<0T=> and <;=>% the privilege to execute a specific procedure can be granted to or revo"ed from application users in order to control data access. -efore creating procedures% the Oracle privileged user named ? =a username often used b# database administrators> must execute a !L script named :-; T:@. !L. The script is commonl# run during the initial creation of an Oracle database and so it is of little conse*uence to #ou as an application developer. 's a developer% #ou cannot create procedures until #ou are granted the C1A'TA P1OCA:<1A s#stem privilege b# #our database administrator. )f #ou are granted the C1A'TA '0? P1OCA:<1A s#stem privilege% then #ou can create procedures &ithin the schemas belonging to other database users. imilarl#% to
1evised+ 11(23(45 13 ( 2

Chapter 13

replace a procedure in another database userBs schema% #ou re*uire the 'LTA1 '0? P1OCA:<1A s#stem privilege. Create Procedure Syntax The general s#ntax to create =or replace> a procedure is sho&n here. The reserved &ords and clauses surrounded b# s*uare brac"ets are optional.
CREATE [OR REPLACE] PROCEDURE <procedure_name> (<parameter1_name> <mode> <data type>, <parameter _name> <mode> <data type>, !!!" #A$%&$' <(ar)a*+e dec+arat)on,> -E.&/ E0ecuta*+e ,tatement, [E1CEPT&O/ E0cept)on 2and+er,] E/D <opt)ona+ procedure name>3

Let us examine each of the clauses and options in detail. The C1A'TA P1OCA:<1A "e#&ords specif# to create a procedure &ith the specified <procedure name> value. The rules for naming a procedure are the same as for naming other Oracle database objects. The O1 1APL'CA optional clause recreates a procedure if it alread# exists &hile maintaining an# procedure privileges previousl# granted to database user accounts. This is useful for modif#ing a procedure since procedures cannot be altered% the# must be dropped and then recreated. )f #ou omit the O1 1APL'CA "e#&ords and the procedure alread# exists% then the C1A'TA statement fails &ith Oracle error message ORA-00955: name is already used by an existing object . )f #ou omit the O1 1APL'CA "e#&ords% then #ou must drop the procedure and create it again in order to modif# the procedure. .or this reason% it is a good idea to use O1 1APL'CA% "eeping in mind that #ou ma# accidentall# replace a procedure that #ou do not intend to replaceC Procedures are generali/ed b# passing parameter values to them. Parameters are enclosed &ithin parentheses. Parameters must have uni*ue names &ithin the procedure. $hen the# contain more than one parameter specification% the# are separated b# commas. The "e#&ord ' is re*uired. ?ou can optionall# use the "e#&ord ) instead of ' , the# &or" identicall#. 9ariables are declared &ithin named procedures in the same fashion as #ou learned in anon#mous PL/ !L bloc"s. This also applies to constants% cursors% and other objects created &ithin a procedure to facilitate data processing. <nli"e parameters% variables can be declared b# specif#ing data t#pe constraints. The executable statements that comprise a procedure are coded in the executable section of the PL/ !L bloc" that is identified b# the -AD)0 "e#&ord. Li"e&ise% exception handlers are created in the optional exception section of the PL/ !L bloc" that is identified b# the A@CAPT)O0 "e#&ord. Procedure Parts ' procedure has t&o parts+ the specification and the bod#. The procedure specification begins &ith the "e#&ord P1OCA:<1A and ends &ith the procedure name or a parameter list. Parameter declarations are optional. Procedures that ta"e no parameters are &ritten &ithout parentheses.
1evised+ 11(23(45 13 ( 3

Chapter 13

The procedure bod# begins &ith the "e#&ord ) =or ' , both ) and ' &or" identicall#> and ends &ith the "e#&ord A0: follo&ed b# an optional procedure name. The procedure bod# has three parts+ a declarative part% an executable part% and an optional exception( handling part. The declarative part contains optional local declarations. :eclarations are declared bet&een the "e#&ords ) and -AD)0. The :ACL'1A "e#&ord% &hich introduces declarations in an anon#mous PL/ !L bloc"% is not used. The executable part can hold one or more coding statements. Coding statements are located -AD)0 and A0:. )f an exception(handling section is coded% then coding statements for the executable part are located bet&een the -AD)0 and A@CAPT)O0 "e#&ords. 't least one statement must appear in the executable part of a procedure. The 0<LL statement meets this re*uirement. The exception(handling part contains exception handlers. The code for these is located bet&een the "e#&ords A@CAPT)O0 and A0: just as #ou learned for an anon#mous PL/ !L bloc". Prior to executing a procedure% #ou must compile and load the procedure into a schema. )n other &ords% #ou have to ma"e it EavailableF in #our logon session. The s#ntax for compiling a schema is sho&n here. ?ou can use either the EGF s#mbol or the T'1T !L command to compile the file. The <S ! "ilename> parameter is the .s*l file that contains the procedure to be compiled.
$4L>5<$4L 6)+ename> or $4L>,tart <$4L 6)+ename>

This is the same command that #ou used to execute an anon#mous PL/ !L bloc". )t is important to understand that the filename does not need to be the same as the procedure name. The .s*l file onl# contains the procedure code. )f the procedure compiles correctl#% it is then stored in the database% not the .s*l file. )n order to execute a procedure at the !L prompt% #ou need to execute the procedure% not the .s*l file. $e &ill return to this topic later in the chapter. Often a procedure &ill not compile correctl#. )n this situation% #ou &ill usuall# be prompted &ith a &arning message. )n order to examine the &arning% issue the command HO$ A11O1 at the !LI prompt.
$4L> ,2o7 error,3

Procedures stored in an Oracle database as database objects are executed &ith the A@AC<TA =A@AC for short> command. The example command sho&n here executes a procedure named #nsert$%mployee.
E1ECUTE &n,ert_Emp+oyee

Parameters -oth procedures and functions can ta"e parameters. 9alues passed as parameters to a procedure as arguments in a calling statement are termed actual parameters. The parameters in a procedure declaration are called "ormal parameters. The difference bet&een these t&o
1evised+ 11(23(45 13 ( J

Chapter 13

classifications is critical to understanding the use of the parameter modes. The values stored in actual parameters are values passed to the formal parameters , the formal parameters are li"e placeholders to store the incoming values. $hen a procedure completes% the actual parameters are assigned the values of the formal parameters. ' formal parameter can have one of three possible modes+ =1> )0% =2>% O<T% or =3> )0 O<T. These modes are outlined in Table 13.1. Table 13.1 Mode )0 O<T )0 O<T Description This t#pe of parameter is passed to a procedure as a read(onl# value that cannot be changed &ithin the procedure. This t#pe of parameter is &rite(onl#% and can onl# appear on the left side of an assignment statement in the procedure. This t#pe of parameter combines both )0 and O<TK a parameter of this mode is passed to a procedure% and its value can be changed &ithin the procedure.

' formal parameter coded as mode )0 receives an actual parameter value% and &ithin the procedure% the value of the formal parameter cannot be changed. )t is read(onl# and acts li"e a constant value. ;ode )0 is the default. ' formal parameters coded as O<T is not passed the value of the corresponding actual parameter. 1ather% it behaves li"e an un(initiali/ed PL/ !L variables and is assigned a 0<LL value. These parameters can have their value changed &ithin a subprogram and the value of the formal parameter is returned to the actual parameter in the calling procedure. The )0 O<T mode combines both )0 and O<T. The value of an actual parameter is passed to the corresponding formal parameter. )n the subprogram% the formal parameter is li"e an initiali/ed PL/ !L variable and it can be modified &ithin the subprogram. $hen the subprogram finishes% the value of the formal parameter is passed bac" to the corresponding actual parameter. ' good programming practice is to use different names for actual and formal parameters. $hen #ou call a procedure% the actual parameters are evaluated and the results are assigned to the corresponding formal parameters. )f necessar#% before assigning the value of an actual parameter to a formal parameter% PL/ !L converts the data t#pe of the value. .or example% if #ou pass a number &hen the procedure expects a string% PL/ !L converts the parameter so that the procedure receives a string. The actual parameter and its corresponding formal parameter must have compatible data t#pes. .or instance% PL/ !L cannot convert bet&een the :'TA and 0<;-A1 data t#pes% or convert a string to a number if the string contains extra characters such as dollar signs. Procedures do not al&a#s return the values of O<T and )0 O<T parameters. )f a procedure raises an exception% the formal parameter values are not copied bac" to their corresponding actual parameters. Procedures do not allo& specif#ing a constraint on the parameter data t#pe. .or example% the follo&ing C1A'TA P1OCA:<1A statement is not allo&ed because of the specification that constrains the &$'ariable parameter to 0<;-A1=2>. )nstead use the general data t#pe of 0<;-A1.
89 &n:a+)d con,tra)nt on parameter! 98 1evised+ 11(23(45 13 ( L

Chapter 13

CREATE OR REPLACE PROCEDURE pro$amp+e (:_(ar)a*+e /U;-ER( ", !!!" 89 (a+)d parameter! 98 CREATE OR REPLACE PROCEDURE pro$amp+e(:_(ar)a*+e /U;-ER, !!!"

Consider the partiall# coded procedure named (pdate%)uipment in PL/ !L Axample 13.1. This procedure has five formal parameters named p$%)uipment*umber% p$+escription% p$,ost% p$ uantity% and p$-roject. Aach is defined &ith a t#pe declaration of MT?PA so that the formal parameters assume a data t#pe that corresponds to the data t#pe of the columns of the e)uipment table of the ;adison Hospital database.
89 PL $4L E0amp+e 1<!1 =)+e> c21<?1!,@+ 98 CREATE OR REPLACE PROCEDURE UpdateE@u)pment ( p_E@u)pment/um*er &/ E@u)pment!E@u)pment/um*erATBPE, p_De,cr)pt)on &/ E@u)pment!De,cr)pt)onATBPE, p_Co,t &/ E@u)pment!Or)C)na+Co,tATBPE, p_4uant)ty &/ E@u)pment!4uant)tyA:a)+a*+eATBPE, p_ProDect &/ E@u)pment!ProDect/um*erATBPE " A$ e_E@u)pment/ot=ound E1CEPT&O/3 :_ErrorTE1T (ARCEAR (F1 "3 -E.&/ UPDATE E@u)pment $ET De,cr)pt)on G p_De,cr)pt)on, Or)C)na+Co,t G p_Co,t, 4uant)tyA:a)+a*+e G p_4uant)ty, ProDect/um*er G p_ProDect HEERE E@u)pment/um*er G p_E@u)pment/um*er3 &= $4LAROHCOU/T G I TEE/ Ra),e e_E@u)pment/ot=ound3 E/D &=3 E1CEPT&O/ HEE/ e_E@u)pment/ot=ound TEE/ D-;$_OUTPUT!PUT_L&/E(J&n:a+)d E@u)pment /um*er> J%% p_E@u)pment/um*er"3 HEE/ OTEER$ TEE/ :_ErrorTe0t >G $4LERR;3 D-;$_OUTPUT!PUT_L&/E(JUne0pected errorJ%%:_ErrorTe0t"3 E/D UpdateE@u)pment3 8

The (pdate%)uipment procedure can be called from another PL/ !L bloc" as sho&n in PL/ !L Axample 13.2. This example declares five variables that are used as actual parameters in the statement that calls the (pdate%)uipment procedure. The value of &$%)uipment*umber is passed to the formal parameter named p$%)uipment*umber% the value of &$+escription is passed to the formal parameter p$+escription% and so forth.
89 PL $4L E0amp+e 1<! =)+e> c21<? !,@+ 98 DECLARE :_E@u)pment/um*er E@u)pment!E@u)pment/um*erATBPE >G JFIIIJ3 :_De,cr)pt)on E@u)pment!De,cr)pt)onATBPE >G JPr)nterJ3 :_Co,t E@u)pment!Or)C)na+Co,tATBPE >G 1K !II3 :_4uant)ty E@u)pment!4uant)tyA:a)+a*+eATBPE >G 3 :_ProDect E@u)pment!ProDect/um*erATBPE >G F3 1evised+ 11(23(45 13 ( N

Chapter 13

-E.&/ UpdateE@u)pment(:_E@u)pment/um*er, :_De,cr)pt)on, :_Co,t, :_4uant)ty, :_ProDect"3 E/D3 8

There are several points that #ou need to understand about calling a procedure and the use of parameters for this example. The (pdate%)uipment procedure is first created% compiled% and stored in the database as a compiled object. The actual parameters are declared &ithin PL/ !L Axample 13.2 and assigned values , the assigned values here merel# illustrate that the parameters &ould have values that are passed to the (pdate%)uipment procedure. The calling statement is a PL/ !L statement b# itself and is not part of an expression , control &ill pass from the calling statement to the first statement inside the procedure. -ecause the formal parameters in (pdate%)uipment are all declared as mode )0% the values of these parameters cannot be changed &ithin the procedure. Comparing Anonymous PL/SQL Blocks with Procedures )n order to contrast anon#mous PL/ !L bloc"s &ith procedures% let us examine the anon#mous PL/ !L bloc" in PL/ !L Axample 13.3.
89 PL $4L E0amp+e 1<!< =)+e> c21<?<!,@+ 98 DECLARE Temp_$a+ary /U;-ER(1I, "3 -E.&/ $ELECT $a+ary &/TO temp_$a+ary =RO; Emp+oyee HEERE Emp+oyee&D G JI1LLFJ3 &= temp_$a+ary > 1FIII TEE/ D-;$_OUTPUT!PUT_L&/E(J$a+ary > 1F,III!J"3 EL$E D-;$_OUTPUT!PUT_L&/E(J$a+ary < 1F,III!J"3 E/D &=3 E1CEPT&O/ HEE/ /O_DATA_=OU/D TEE/ D-;$_OUTPUT!PUT_L&/E(JEmp+oyee not 6ound!J"3 E/D3 8

The anon#mous PL/ !L bloc" in PL/ !L Axample 13.3 stores a value from the Salary column of the employee table to a temporar# variable named tempSalary for the emplo#ee &ith identifier 4133L. .ollo&ing this% a line of output is produced depending on the value of tempSalary. Aver# time the code of the anon#mous PL/ !L bloc" executes% PL/ !L must first parse the code. Contrast this &ith the creation and execution of the procedure named +isplaySalary that is given in PL/Axample 13.J. ince the procedure is stored to the database% it is onl# parsed
1evised+ 11(23(45 13 ( 5

Chapter 13

and compiled once. Thereafter% the compiled version of the procedure is executed. procedure onl# re*uires recompilation if it is dropped and created again.
89 PL $4L E0amp+e 1<!M =)+e> c21<?M!,@+ 98 CREATE OR REPLACE PROCEDURE D),p+ay$a+ary &$ ?? create +oca+ :ar)a*+e 7)t2 re@u)red con,tra)nt temp_$a+ary /U;-ER(1I, "3 -E.&/ $ELECT $a+ary &/TO temp_$a+ary =RO; Emp+oyee HEERE Emp+oyee&D G JI1LLFJ3 &= temp_$a+ary > 1FIII TEE/ D-;$_OUTPUT!PUT_L&/E(J$a+ary > 1F,III!J"3 EL$E D-;$_OUTPUT!PUT_L&/E(J$a+ary < 1F,III!J"3 E/D &=3 E1CEPT&O/ HEE/ /O_DATA_=OU/D TEE/ D-;$_OUTPUT!PUT_L&/E(JEmp+oyee not 6ound!J"3 E/D D),p+ay$a+ary3 8

The

?ou can create the procedure b# issuing the appropriate command to run the file that stores the code to create the procedure at the !L prompt as sho&n here =either .c/01-23s)l or start c/01-23s)l>. 'lternativel#% #ou can cop#/paste the entire C1A'TA P1OCA:<1A statement =including all code> &ithin !L6Plus and execute the code. This &ill also create the procedure. ' successful creation results in the -rocedure created message. The procedure can be executed &ith the exec <procedure name> command. Here the procedure is executed and the output displa#ed is+ Salary > 054000.
$4L> 5c21<?M!,@+ Procedure created! $4L> e0ec D),p+ay$a+ary $a+ary > 1F,III! PL8$4L procedure ,ucce,,6u++y comp+eted!

Passing ! and "#$ Parameter 's #ou learned earlier% in order to pass values to and return values from a procedure% #ou need to define variables in the implicit declaration section of a procedure. PL/ !L Axample 13.L provides an example &ith )0 and O<T variables.
89 PL $4L E0amp+e 1<!F =)+e> c21<?F!,@+ 98 CREATE OR REPLACE PROCEDURE D),p+ay$a+ary (p_Emp+oyee&D &/ CEAR, p_$a+ary OUT /U;-ER" &$ :_$a+ary /U;-ER(1I, "3 -E.&/ 1evised+ 11(23(45 13 ( 3

Chapter 13

$ELECT $a+ary &/TO :_$a+ary =RO; Emp+oyee HEERE Emp+oyee&D G p_Emp+oyee&D3 &= :_$a+ary > 1FIII TEE/ D-;$_OUTPUT!PUT_L&/E(J$a+ary > 1F,III!J"3 EL$E D-;$_OUTPUT!PUT_L&/E(J$a+ary <G 1F,III!J"3 E/D &=3 p_$a+ary >G :_$a+ary3 E1CEPT&O/ HEE/ /O_DATA_=OU/D TEE/ D-;$_OUTPUT!PUT_L&/E(JEmp+oyee not 6ound!J"3 E/D D),p+ay$a+ary 3 8

)n this revision of the +isplaySalary procedure% t&o formal parameters correspond to actual parameters of a calling procedure , p$%mployee#+ as an )0 parameter and p$Salary as an O<T parameter. The value of pOAmplo#ee): is received from the actual parameter &hile the value of pO alar# is initiall# assigned a value of 0<LL. ' local variable named &$Salary is created and the ALACT statement stores a value to this variable from the employee table. The output displa#ed b# the procedure depends upon &hether or not the salar# is greater than or less than the P1L%444 salar# cut(off level. -efore exiting% the value of &$Salary is assigned to the p$Salary O<T parameter. ?ou can test calling the procedure b# executing the anon#mous PL/ !L bloc" sho&n in PL/ !L Axample 13.N. This PL/ !L bloc" declares a parameter variable named &$Salary and then calls the procedure b# providing a value of 4133L for the p$%mployee#+ )0 formal parameter and the parameter variable &$Salary for the p$Salary O<T formal parameter. 0ote that &hile the variable &$Salary in the calling procedure is the same name as the variable &$Salary in the :ispla# alar#2 procedure% these are% in fact% t&o completel# different local variables. The output produced to the computer monitor screen consists of one line of output produced b# the stored procedure =Salary > 054000.> and a second line of output that displa#s the value of the salar# that is returned to the calling anon#mous PL/ !L bloc" = Actual salary: 05650>.
89 PL $4L E0amp+e 1<!N =)+e> c21<?N!,@+ 98 DECLARE :_$a+aryOutput /U;-ER >G I3 -E.&/ ?? ca++ t2e procedure D),p+ay$a+ary (JI1LLFJ, :_$a+aryOutput"3 ?? d),p+ay :a+ue o6 ,a+ary a6ter t2e ca++ D-;$_OUTPUT!PUT_L&/E(JActua+ ,a+ary> J%%TO_CEAR(:_$a+aryOutput""3 E/D3 8 $a+ary > 1F,III! Actua+ ,a+ary> 1N FI PL8$4L procedure ,ucce,,6u++y comp+eted!

1evised+ 11(23(45

13 ( Q

Chapter 13

#sing Bind %aria&les Let us revie& PL/ !L Axamples 13.L and 13.N again. The +isplaySalary6 procedure ta"es t&o parameters% one )0 variable and one O<T variableR )n PL/ !L Axample 13.N the variable &$SalaryOutput to hold the output value returned from the procedure. The short anon#mous PL/ !L bloc" in PL/ !L Axample 13.N is used to test the :ispla# alar#2 procedure. Ho&ever% another approach can be used to test a procedure. This approach uses a bind &ariable in Oracle. ' bind variable is a variable created at the !L6Plus prompt that is used to reference variables in PL/ !L subprograms. $hen #ou create a bind variable in !L6Plus% #ou can use it li"e a variable in a PL/ !L programs and access the variable from !L6Plus. ' bind variable is created at the !LI prompt &ith the &ar statement as sho&n in PL/ !L Axample 13.5. The procedure is *uic"l# executed &ith the A@AC statement. )n the A@AC statement% t&o parameter values are passed to the called procedure =1> a emplo#ee identifier of 4133L and =2> the &$SalaryOutput bind variable. ' bind variable used in this fashion must be prefixed &ith a colon E+F , this s#ntax is re*uiredK other&ise% Oracle &ill return a -!S-00600: identi"ier 7'$SA!AR8O(9-(97 must be declared error message. ?ou can examine the value returned to the variable &ith a P1)0T statement.
89 PL $4L E0amp+e 1<!K 98 $4L> :ar :_$a+aryOutput /U;-ER3 $4L> E1EC D),p+ay$a+ary (JI1LLFJ, >:_$a+aryOutput"3 $a+ary > 1F,III! PL8$4L procedure ,ucce,,6u++y comp+eted! $4L> PR&/T :_$a+aryOutput3 (_$ALARBOUTPUT ?????????????? 1N FI

Dropping a Procedure The !L statement to drop a procedure is the straight(for&ard :1OP P1OCA:<1A Sprocedure0ameI command. Teep in mind that this is a data definition language =::L> command% and so an implicit commit executes prior to and immediatel# after the command.
$4L> DROP PROCEDURE D),p+ay$a+ary 3 Procedure dropped!

FUNCTIONS )n PL/ !L% there is little difference bet&een function and procedure subprograms. The primar# difference is that a function can return onl# a single value and values are returned through use of a 1AT<10 statement.

1evised+ 11(23(45

13 ( 14

Chapter 13

Create 'unction Syntax Li"e a procedure% a function can accept multiple parameters% and the data t#pe of the return value must be declared in the header of the function. The general s#ntax to create =or replace> a function is sho&n here. 's &ith procedures% the reserved &ords and clauses surrounded b# s*uare brac"ets are optional.
CREATE [OR REPLACE =U/CT&O/] <6unct)on_name> (<parameter1_name> <mode> <data type>, <parameter _name> <mode> <data type>, !!!" RETUR/ <6unct)on return :a+ue data type> #A$%&$' <(ar)a*+e dec+arat)on,> -E.&/ E0ecuta*+e Command, RETUR/ (return_:a+ue"3 ! ! ! [E1CEPT&O/ E0cept)on 2and+er,] E/D3

The general s#ntax of the 1AT<10 statement is+


RETUR/ <e0pre,,)on>3

The SexpressionI in a 1AT<10 statement is the value returned b# the function. The 1AT<10 statement returns the value and program control to the calling environment. )t is not necessar# for the 1AT<10 statement to appear in the last line of the executable section. .urther% the code ma# contain more than one 1AT<10 statement% but onl# one 1AT<10 statement can execute. ' function that ends &ithout executing a 1AT<10 statement &ill generate an error. 's &ith procedures% the O1 1APL'CA clause is optional. PL/ !L Axample 13.3 creates the Retrie&eSalary function , an example function that has no parameters. $hen a subprogram =procedure or function> has no parameters% the object is declared &ithout the parentheses that normall# enclose the parameter list. The Retrie&eSalary function retrieves the emplo#ee salar# for a specific emplo#ee into the variable named &$Salary and then returns the value of that variable..
89 PL $4L E0amp+e 1<!L =)+e> c21<?L!,@+ 98 CREATE OR REPLACE =U/CT&O/ Retr)e:e$a+ary RETUR/ /U;-ER &$ :_$a+ary /U;-ER(1I, "3 -E.&/ $ELECT $a+ary &/TO :_$a+ary =RO; Emp+oyee HEERE Emp+oyee&D G JI1LLFJ3 RETUR/ :_$a+ary3 E/D Retr)e:e$a+ary3 8

?ou create functions just as #ou did &ith procedures b# issuing either a GSfunction nameI or startSfunction nameI statement at the !L prompt as sho&n in PL/ !L Axample
1evised+ 11(23(45 13 ( 11

Chapter 13

13.Q. ?ou can also cop#/past the code for a function to the !L prompt. ?ou can test the Retrie&eSalary function b# using a bind variable.
89 PL $4L E0amp+e 1<!O 98 $4L> 5Retr)e:e$a+ary =unct)on created! $4L> :ar :_$a+aryOutput /U;-ER3 $4L> E1EC >:_$a+aryOutput >G Retr)e:e$a+ary3 PL8$4L procedure ,ucce,,6u++y comp+eted! $4L> pr)nt :_$a+aryOutput3 (_$ALARBOUTPUT ?????????????? 1N FI

PL/ !L Axample 13.Q illustrates a function that has a single )0 parameter and that returns a 9'1CH'12 data t#pe. This function accepts the Amplo#ee): column value and returns the full name of the emplo#ee including the last name% first name% and middle initial. .our local variables are used in the function. The &$:ull*ame variable stores the computed value of the full name &hile the other three local variables store column values selected from the employee table. 'n ). statement adds the middle initial if the emplo#ee has a middle name that is at least one character in length.
89 PL $4L E0amp+e 1<!O =)+e> c21<?O!,@+ 98 CREATE OR REPLACE =U/CT&O/ =u++/ame(p_Emp+oyee&D &/ emp+oyee!Emp+oyee&D ATBPE" RETUR/ (ARCEAR &$ :_=u++/ame (ARCEAR (1II"3 :_=)r,t/ame emp+oyee!=)r,t/ameATBPE3 :_;)dd+e/ame emp+oyee!;)dd+e/ameATBPE3 :_La,t/ame emp+oyee!La,t/ameATBPE3 -E.&/ $ELECT =)r,t/ame, ;)dd+e/ame, La,t/ame &/TO :_=)r,t/ame, :_;)dd+e/ame, :_La,t/ame =RO; Emp+oyee HEERE Emp+oyee&D G p_Emp+oyee&D3 ?? $tore +a,t name, comma and *+anP and 6)r,t name to :ar)a*+e :_=u++/ame >G :_La,t/ame%%J, J%%:_=)r,t/ame3 ?? C2ecP 6or e0),tence o6 a m)dd+e name &= LE/.TE(:_;)dd+e/ame" > I TEE/ :_=u++/ame >G :_=u++/ame%%J J%%$U-$TR(:_;)dd+e/ame,1,1"%%J!J3 E/D &=3 RETUR/ :_=u++/ame3 E/D =u++/ame3 8 1evised+ 11(23(45 13 ( 12

Chapter 13

' simple ALACT statement executed &ithin !L6Plus can return the full name for an# emplo#ee identifier value as sho&n in PL/ !L Axample 13.14.
89 PL $4L E0amp+e 1<!1I 98 $4L> $ELECT =u++/ame(JI1LLFJ" =RO; Emp+oyee < HEERE Emp+oyee&D G JI1LLFJ3 =ULL/A;E(JI1LLFJ" ??????????????????????????????????? -ocP, DouC+a, -!

The function is *uite versatile as illustrated in this ALACT statement of PL/ !L Axample 13.11 that selects all employee table ro&s and orders the output alphabeticall#.
89 PL $4L E0amp+e 1<!11 98 $4L> $ELECT =u++/ame(Emp+oyee&D" =RO; Emp+oyee < ORDER -B =u++/ame(Emp+oyee&D"3 =ULL/A;E(E;PLOBEE&D" ????????????????????????????????????? Adam,, Adam A! -ar+o7, H)++)am A! -ecPer, Ro*ert -! -ecPer, Ro*erta .! -ocP, DouC+a, -! !!! more ro7, 7)++ d),p+ay

Dropping a 'unction 's &ith the :1OP P1OCA:<1A statement% the :1OP .<0CT)O0 Sfunction0ameI is also straight(for&ard. 's &ith :1OP P1OCA:<1A% the :1OP .<0CT)O0 statement is a ::L command that causes execution of an implicit commit prior to and immediatel# after the command.
$4L> DROP =U/CT&O/ =u++/ame3 =unct)on dropped!

PACKAGES ' pac"age is a collection of PL/ !L objects grouped together under one pac"age name. Pac"ages provide a means to collect related procedures% functions% cursors% declarations% t#pes% and variables into a single% named database object that is more flexible than the related database objects are b# themselves. Consider the use of variable. 'll of the variables that #ou have used thus far in procedures and functions are local variables% meaning the# are visible onl# in the subprogram in &hich the# are declared. 's soon as the subprogram terminates% the variable goes out of scope and the memor# allocated to the subprogram for the variable is returned for reuse b# the computer operating s#stem. The variable cannot be accessed again. ometimes it is useful and even necessar# to create global variables that store values to be shared among man# PL/ !L
1evised+ 11(23(45 13 ( 13

Chapter 13

subprograms. ' global variable is declared &ithin a pac"age b# using the same s#ntax used to declare a local variable. $hile local variables are declared in the :ACL'1A section of an individual subprogram% global variables are declared in the :ACL'1A section of a pac"age. Package Speci(ication and Scope ' pac"age consists of a pac"age specification and a pac"age bod#. The pac;age speci"ication% also called the pac"age header% declares global variables% cursors% exceptions% procedures% and functions that can be called or accessed b# other program units. ' pac"age specification must be a uni*uel# named database object. Alements of a pac"age can declared in an# order. )f element E'F is referenced b# another element% then element E'F must be declared before it is referenced b# another element. .or example% a variable referenced b# a cursor must be declared before it is used b# the cursor. :eclarations of subprograms must be for&ard declarations. This means the declaration onl# includes the subprogram name and arguments% but does not include the actual program code. The code of a subprogram that is part of a pac"age is placed in the pac"age bod#. Create Package Syntax -asicall#% a pac"age is a named declaration section. 'n# object that can be declared in a PL/ !L bloc" can be declared in a pac"age. To create a pac"age specification% use the C1A'TA O1 1APL'CA P'CT'DA clause. )nclude the specification of each named PL/ !L bloc" header that &ill be public &ithin the pac"age. Procedures% functions% cursors% and variables that are declared in the pac"age specification are global. The basic s#ntax for a pac"age is+
CREATE [OR REPLACE PACQA.E[ <pacPaCe name> #A$%&$' <:ar)a*+e dec+arat)on,>3 <cur,or dec+arat)on,>3 <procedure and 6unct)on dec+arat)on,>3 E/D <pacPaCe name>3

To declare a procedure in a pac"age% #ou must specif# the procedure name% follo&ed b# the parameters and variable t#pes using the follo&ing format+
PROCEDURE <procedure_name> (param1 param1datatype, param param datatype, !!!"3

To declare a function in a pac"age% #ou must specif# the function name% parameters and return variable t#pe using the follo&ing format+
=U/CT&O/ <6unct)on_name> (param1 param1datatype, param param datatype, !!!" RETUR/ <return data type>3

Package Body ' pac"age bod# contains the code for the subprograms and other constructs% such as exceptions% that are declared in the pac"age specification. The pac"age bod# is optional. '
1evised+ 11(23(45 13 ( 1J

Chapter 13

pac"age that contains onl# variable declarations% cursors% and the li"e% but no procedure or function declarations does not re*uire a pac"age bod#. 'n# subprograms declared in a pac"age must be coded completel# in the pac"age bod#. The procedure and function specifications of the pac"age bod# must match the pac"age declarations including subprogram names% parameter names% and parameter modes. Create Package Body Syntax <se the C1A'TA O1 1APL'CA P'CT'DA -O:? clause to create a pac"age bod#. The basic s#ntax is+
CREATE [OR REPLACE] PACQA.E -ODB <pacPaCe_name> A$ <cur,or ,pec)6)cat)on,> <,u*proCram ,pec)6)cat)on, and code> E/D <pacPaCe name>3

An )xample Package PL/ !L Axample 13.12 contains the code for a pac"age named <anage%mployee. The pac"age specification includes declarations for a procedure named :ind%mployee and a function named =ood#denti"ier. )t also declares an exception named e$%mployee#+*ot:ound that can be raised b# the :ind%mployee procedure% or an# other procedure that ma# later be added to the pac"age that re*uires such an exception.
89 PL $4L E0amp+e 1<!1 =)+e> c21<?1 !,@+ 98 CREATE OR REPLACE PACQA.E ;anaCeEmp+oyee A$ ?? .+o*a+ :ar)a*+e dec+arat)on, Co 2ere ?? Procedure to 6)nd emp+oyee, PROCEDURE =)ndEmp+oyee( emp_&D &/ emp+oyee!Emp+oyee&DATBPE, emp_=)r,t/ame OUT emp+oyee!=)r,t/ameATBPE, emp_La,t/ame OUT emp+oyee!La,t/ameATBPE"3 ?? E0cept)on ra),ed *y =)ndEmp+oyee e_Emp+oyee&D/ot=ound E1CEPT&O/3 ?? =unct)on to determ)ne )6 emp+oyee )dent)6)er ), :a+)d =U/CT&O/ .ood&dent)6)er( emp_&D &/ emp+oyee!Emp+oyee&DATBPE" RETUR/ -OOLEA/3 E/D ;anaCeEmp+oyee3 8

ince the <anage%mployee pac"age contains t&o for&ard declarations of subprograms% a pac"age bod# is needed to create the subprograms. -ecause the PL/ !L bloc"s are not being created as separate database objects% the# do not re*uire a C1A'TA O1 1APL'CA clause. PL/ !L Axample 13.13 gives the <anage%mployee pac"age bod#.
89 PL $4L E0amp+e 1<!1< =)+e> c21<?1<!,@+ 98 1evised+ 11(23(45

13 ( 1L

Chapter 13

CREATE OR REPLACE PACQA.E -ODB ;anaCeEmp+oyee A$ ?? Procedure to 6)nd emp+oyee, PROCEDURE =)ndEmp+oyee( emp_&D &/ emp+oyee!Emp+oyee&DATBPE, emp_=)r,t/ame OUT emp+oyee!=)r,t/ameATBPE, emp_La,t/ame OUT emp+oyee!La,t/ameATBPE " A$ -E.&/ $ELECT =)r,t/ame, La,t/ame &/TO emp_=)r,t/ame, emp_La,t/ame =RO; Emp+oyee HEERE Emp+oyee&D G emp_&D3 ?? C2ecP 6or e0),tence o6 emp+oyee &= $4LAROHCOU/T G I TEE/ RA&$E e_Emp+oyee&D/ot=ound3 E/D &=3 E/D =)ndEmp+oyee3 ?? =unct)on to determ)ne )6 emp+oyee )dent)6)er ), :a+)d =U/CT&O/ .ood&dent)6)er( emp_&D &/ emp+oyee!Emp+oyee&DATBPE" RETUR/ -OOLEA/ &$ :_&D_Count /U;-ER3 -E.&/ $ELECT COU/T(9" &/TO :_&D_Count =RO; Emp+oyee HEERE Emp+oyee&D G emp_&D3 ?? return TRUE )6 :_&D_COU/T ), 1 RETUR/ (1 G :_&D_Count"3 E1CEPT&O/ HEE/ OTEER$ TEE/ RETUR/ =AL$E3 E/D .ood&dent)6)er3 E/D ;anaCeEmp+oyee3 8

Calling Package "&*ects Objects declared in a pac"age are visible outside of a pac"age b# *ualif#ing the object &ith the pac"age name. Consider a pac"age named <anage%mployee that contains a procedure named (pdate%mployee. The procedure can be referenced using the follo&ing s#ntax+
;anaCeEmp+oyee,!UpdateEmp+oyee(<parameter, Co 2ere>"3

PL/ !L Axample 13.1J is an anon#mous PL/ !L bloc" that calls the :ind%mployee procedure of the <anage%mployee pac"age. 'n emplo#ee identifier value is entered for the searc/$#+ substitution variable. 0ote the value is entered including single(*uote mar"s.
89 PL $4L E0amp+e 1<!1M =)+e> c21<?1M!,@+ 98 1evised+ 11(23(45 13 ( 1N

Chapter 13

DECLARE :_=)r,t/ame emp+oyee!=)r,t/ameATBPE3 :_La,t/ame emp+oyee!La,t/ameATBPE3 ,earc2_&D emp+oyee!Emp+oyee&DATBPE3 -E.&/ ;anaCeEmp+oyee!=)ndEmp+oyee(R,earc2_&D, :_=)r,t/ame, :_La,t/ame"3 D-;$_OUTPUT!PUT_L&/E(JT2e emp+oyee name ),> J %% :_La,t/ame %% J, J %% :_=)r,t/ame"3 E1CEPT&O/ HEE/ OTEER$ TEE/ D-;$_OUTPUT!PUT_L&/E(JCannot 6)nd an emp+oyee 7)t2 t2at &D!J"3 E/D3 8

$hen the emplo#ee identifier is valid% the code displa#s the emplo#ee name as sho&n here.
Enter :a+ue 6or ,earc2_)d> JI1LLFJ T2e emp+oyee name ),> -ocP, DouC+a, PL8$4L procedure ,ucce,,6u++y comp+eted!

$hen the identifier is not valid% the exception raised &ithin the called procedure is propagated bac" to the calling procedure and is trapped b# the A@CAPT)O0 sectionBs $HA0 OTHA1 clause and an appropriate message is displa#ed as sho&n here.
Enter :a+ue 6or ,earc2_)d> JOOOOOJ Cannot 6)nd an emp+oyee 7)t2 t2at &D! PL8$4L procedure ,ucce,,6u++y comp+eted!

Cursors in Packages 's #ou learned in Chapter 12% a cursor can populate the result set of a multiple ro& *uer#. Ho&ever% a cursor is static because it is tied to a specific *uer# inside a function or procedure. The use of a cursor &ariable can ma"e a cursor d#namic so that it is reusable and sharable among different procedures and functions such as those created as part of a pac"age. ' cursor variable has data t#pe 1A. C<1 O1. )t is li"e a pointer in the C language% and it points to a *uer# &or" area &here a result set is stored. Therefore% the cursor can be passed freel# as a parameter to other subprograms. To create a cursor variable% #ou have to define a 1A. C<1 O1 t#pe. 0ext% #ou define a cursor variable of that t#pe. )n this general s#ntactic example% the SreturnOt#peI object represents a ro& in a database table.
TBPE re6_type_name &$ RE= CUR$OR [RETUR/ <return_type>]3

This provides an example of declaring a cursor variable that can be used to process data ro&s for the e)uipment table of the ;adison Hospital database.
DECLARE TBPE e@u)pment_Type &$ RE= CUR$OR RETUR/ e@u)pmentAROHTBPE3 c:_E@u)pment &/ OUT e@u)pment_Type3 1evised+ 11(23(45 13 ( 15

Chapter 13

PL/ !L Axample 13.1L demonstrates the use of 1A. cursors in a pac"age named <anage%)uipment. The code that creates the pac"age specification declares a 1A. C<1 O1 t#pe named e)uipment$9ype. )t also declares t&o procedures named Open#tem and :etc/#tem. 0ote that the cursor variable c&$%)uipment declared in the Open#tem procedure is declared as an )0 O<T parameter. This means that the variable &ill store an item after the procedure is executedUit is this stored value that is input to the :etc/#tem procedure. The code in PL/ !L Axample 13.1N creates the associated pac"age bod#.
89 PL $4L E0amp+e 1<!1F =)+e> c21<?1F!,@+ 98 CREATE OR REPLACE PACQA.E ;anaCeE@u)pment A$ ?? Create RE= CUR$OR type TBPE e@u)pment_Type &$ RE= CUR$OR RETUR/ e@u)pmentAROHTBPE3 ?? Dec+are procedure PROCEDURE Open&tem(c:_E@u)pment &/ OUT e@u)pment_Type, p_E@u)pment/um*er &/ CEAR"3 ?? Dec+are procedure to 6etc2 an e@u)pment )tem PROCEDURE =etc2&tem(c:_E@u)pment &/ e@u)pment_Type, e@u)pment_Ro7 OUT e@u)pmentAROHTBPE"3 E/D ;anaCeE@u)pment3 8 89 PL $4L E0amp+e 1<!1N =)+e> c21<?1N!,@+ 98 CREATE OR REPLACE PACQA.E -ODB ;anaCeE@u)pment A$ ?? Procedure to Cet a ,pec)6)c )tem o6 e@u)pment PROCEDURE Open&tem(c:_E@u)pment &/ OUT e@u)pment_Type, p_E@u)pment/um*er &/ CEAR" A$ -E.&/ ?? Popu+ate t2e cur,or OPE/ c:_E@u)pment =OR $ELECT 9 =RO; E@u)pment HEERE E@u)pment/um*er G p_E@u)pment/um*er3 E/D Open&tem3 PROCEDURE =etc2&tem(c:_E@u)pment &/ e@u)pment_Type, e@u)pment_Ro7 OUT e@u)pmentAROHTBPE" A$ -E.&/ =ETCE c:_E@u)pment &/TO e@u)pment_Ro73 E/D =etc2&tem3 E/D ;anaCeE@u)pment3 8

The anon#mous PL/ !L bloc" in PL/ !L Axample 13.15 uses procedures defined in the <anage%)uipment pac"age to print the e*uipment description for the e*uipment number assigned to the &$%)uipment*umber variable &ithin the program. Here the value is hard(coded for illustration purposes as e*uipment number VL441B , the program produces the description of this item of e*uipment+ ,omputer4 +es;top.
1evised+ 11(23(45 13 ( 13

Chapter 13

89 PL $4L E0amp+e 1<!1N =)+e> c21<?1N!,@+ 98 DECLARE ?? Dec+are a cur,or :ar)a*+e o6 t2e RE= CUR$OR type ?? dec+ared )n t2e ;anaCeE@u)pment pacPaCe )tem_Cur,or ;anaCeE@u)pment!e@u)pment_Type3 :_E@u)pment/um*er e@u)pment!E@u)pment/um*erATBPE3 e@u)pment_Ro7 e@u)pmentAROHTBPE3 -E.&/ ?? A,,)Cn a e@u)pment num*er to t2e :ar)a*+e :_E@u)pment/um*er >G JFII1J3 ?? Open t2e cur,or u,)nC a :ar)a*+e ;anaCeE@u)pment!Open&tem()tem_Cur,or, :_E@u)pment/um*er"3 ?? =etc2 t2e e@u)pment data and d),p+ay )t LOOP ;anaCeE@u)pment!=etc2&tem()tem_Cur,or, e@u)pment_Ro7"3 E1&T HEE/ )tem_cur,orA/OT=OU/D3 D-;$_OUTPUT!PUT(e@u)pment_Ro7!E@u)pment/um*er %% J J"3 D-;$_OUTPUT!PUT_L&/E(e@u)pment_Ro7!De,cr)pt)on"3 E/D LOOP3 E/D3 8 FII1 Computer, De,Ptop

PL8$4L procedure ,ucce,,6u++y comp+eted!

Ad+antages o( Packages 0o& that #ou have examined several pac"ages% #ou have probabl# begun to appreciate this approach to combining related PL/ !L bloc"s. The advantages of pac"ages are summari/ed in Table 13.2 Table 13.2 ;odularit# ;ore .lexible 'pplication :evelopment Pac"age )ntegrit# ' pac"age allo&s #ou to encapsulate related subprogramsUthis modularit# improves an application programmerBs understanding of ho& the various components of an application are related. To design a pac"age application% #ou must first specif# the objects or subprograms in a pac"age specification. 'fter compiling the pac"age specification% the stored subprograms that refer to the pac"age can be compiled. Therefore% &e need not define the pac"age bod# completel#% until &e are read# &ith the specification of the application. )n other &ords% &e can code and compile a pac"age specification &ithout its bod# Pac"ages enable the coding of both private and public database objects , this approach enables #ou as a developer to protect the integrit# of the pac"age. .or example% consider a pac"age that consists of four subprograms% three public and one private. The pac"age hides the definition of the private subprogram so that onl# the pac"age =not the application> is affected if the subprogram definition changes. Thus% the implementation details are hidden from other users% thereb# protecting the integrit# of the pac"age.
13 ( 1Q

1evised+ 11(23(45

Chapter 13

'dded .unctionalit# -etter Performance

Public objects and cursors declared in a pac"age specification can be shared b# all procedures executed in the environment because the public objects and cursors persist for the duration of a session. $hen an application program calls a pac"age the first time% the entire pac"age is loaded in the memor#. ubse*uent calls re*uire no dis" input/output.

DATABASE TRIGGERS ' database trigger is a stored PL/ !L program unit that is associated &ith a specific database table% or &ith certain vie& t#pes. ' database trigger can also be associated &ith a s#stem event such as database startup. ;an# #ears ago &hen triggers as database objects &ere first created% database administrators and application developers used the term EfiringF to describe an event such as the insertion of a ne& table ro& that &ould execute a trigger. This is ho& the term Edatabase triggerF evolved. O1'CLA executes =fires> a database trigger automaticall# &hen a given !L :;L operation% such as an )0 A1T% <P:'TA% or :ALATA affects one or more ro&s of a table. $hile procedures and functions must be explicitl# invo"ed% database triggers are implicitl# invo"ed. :atabase triggers can be used to perform an# of the follo&ing tas"s+ 'udit data modification. Log events transparentl#. Anforce complex business rules. :erive column values automaticall#. )mplement complex securit# authori/ations. ;aintain replicate tables. Publish information about events for a publish(subscribe environment such as that associated &ith &eb programming.

Li"e procedures and functions% triggers are named PL/ !L bloc"s &ith declarative% executable% and exception handling sections. Triggers are stand(alone database objects , the# are not stored as part of a pac"age and cannot be local to a bloc". 'lso% triggers do not accept arguments. $hen #ou create a database trigger% #ou &ill normall# assume o&nership of the trigger% although o&nership can be transferred to another user. )n order to create and test a trigger% #ou =not the s#stem user of the trigger> must have appropriate access to all objects referenced b# a trigger action. .or example% if #ou create a -A.O1A )0 A1T trigger for the employee table% then #ou must have the )0 A1T 1O$ privilege for the table. There are a fe& limitations &ith database triggers. ' trigger cannot contain the CO;;)T% 1OLL-'CT% and '9APO)0T statements. ?ou must be careful &hen using triggers as the trigger ma# cause the coding bloc" to execute thousands of times for a large update seriousl# affect !L execution performance. 'lso% the trigger bod# cannot exceed 32T in si/e. Triggers larger than this can have part of their code moved to one or more compiled stored procedures that are called from the trigger. There is no longer a limit on the number of triggers defined for a :;L statement for a table. )n fact% #ou can define t&o triggers of the same t#pe for a table. ?ou might define t&o
1evised+ 11(23(45 13 ( 24

Chapter 13

different )0 A1T triggers for the employee table of the ;adison Hospital database. $hen this occurs% the triggers of the same t#pe fire se*uentiall#. Create $rigger Syntax The s#ntax for creating a trigger is sho&n here. surrounded b# s*uare brac"ets are optional. The reserved &ords and clauses

CREATE [OR REPLACE] TR&..ER tr)CCer_name #-E=ORE%A=TER%&/$TEAD O=' tr)CCer)nC_e:ent [re6erenc)nC_c+au,e] O/ #ta*+e_name % :)e7_name' [HEE/ cond)t)on] [=OR EACE ROH] DECLARE Dec+arat)on ,tatement, [-E.&/ E0ecuta*+e ,tatement, E1CEPT&O/ E0cept)on?2and+)nC ,tatement,] E/D3

's &ith procedures and functions% the C1A'TA T1)DDA1 clause creates a trigger &ith the specified name. 'dditionall#% the O1 1APL'CA clause is optional and &or"s in the same &a# that it does &hen creating a procedure or function. The trigger bod# must have at least the executable section. The declarative and exception handling sections are optional. $hen there is a declarative section% the trigger bod# must start &ith the :ACL'1A "e#&ord. ' trigger bod# is the PL/ !L bloc" that contains the !L or PL/ !L code that executes for a triggering statement. Li"e stored procedures% a trigger action can call !L or PL/ !L statements% and define PL/ !L language constructs =variables% constants% cursors% exceptions% and so on>. The -A.O1A% '.TA1% and )0 TA': O. "e#&ords specif# &hen a trigger fires , before or after a triggering event% or instead of the triggering event. The -A.O1A and '.TA1 "e#&ord specifications appl# to tables. 'n )0 TA': O. trigger is onl# applicable to vie&s. The triggering$e&ent references a :;L statement issued against the table or vie& named in the O0 clause. The triggeringOevent specifies the table name =and an optional column name> on &hich a trigger fires. ' :;L trigger specified &ith a -A.O1A option causes Oracle to fire the trigger before executing the triggering :;L statement. On the other hand% an '.TA1 option causes Oracle to fire a trigger after executing the triggering statement. 'n )0 TA': O. trigger for a vie& causes the triggering statement to not fire at allK instead% the triggering statement is replaced b# an alternative set of one or more !L statements &ithin the bod# of the trigger. The re"erencing$clause is not used ver# often. $hen used% it enables #ou to &rite code to refer to the data in the ro& currentl# being modified b# a different name. 1estrictions on a trigger are set b# specif#ing a -oolean expression &ith a $HA0 clause% as sho&n in the s#ntax for creating triggers. The $HA0 clause specifies that a trigger is to fire onl# &hen a specific condition is met. Consider the situation &here a customer order for credit is *uite large. ' trigger might be &ritten to re*uire customer order approval &hen the credit re*uested exceeds a certain maximum credit level.
HEE/ (ne7!OrderTota+ > :_;a0)mumCred)t" 1evised+ 11(23(45 13 ( 21

Chapter 13

,hen $riggers 'ire ' trigger ma# be a 1O$ or T'TA;A0T t#pe of trigger. )f the .O1 A'CH 1O$ clause is present in the C1A'TA T1)DDA1 command% then the trigger is a 1O$ trigger. ' 1O$ trigger is fired for each ro& affected b# a triggering statement. .or example% an <P:'TA trigger on the emplo#ee table &ill fire for ever# ro& affected b# an <P:'TA statement. ' T'TA;A0T trigger% ho&ever% is fired onl# once for the triggering statement% regardless of the number of ro&s affected b# the triggering statement. Oracle specifies rules for the order b# &hich :;L statements are executed and triggers are fired. The order is+ 1. Axecuted before statement(level triggers =if there are an#>. 2. .or each ro& affected b# a :;L statement+ a. Axecute before ro&(level triggers =if there are an#>. b. Axecute the :;L statement. c. Axecute after ro&(level triggers =if there are an#>. 3. Axecute after statement(level triggers =if there are an#>. S$A$)M)!$ $rigger )xample PL/ !L Axample 13.15 defines an example of a T'TA;A0T trigger because it executes onl# once for the associated :;L statement% not for ever# ro&. The Secure%mployee trigger can fire &hen deleting% inserting% or updating an employee table ro&. This particular trigger uses the 1') AO'PPL)C'T)O0OA11O1 statement to inform the application user that the table is secure and cannot be modified on a &ee"end da# = aturda# or unda#>. The table also cannot be modified prior to 3+34 a.m. or after N+34 p.m. 1emember% #ou can customi/e error conditions &ith the 1') AO'PPL)C'T)O0OA11O1 procedure to displa# an error number =error numbers must be bet&een (2441 and (24QQQ> and an appropriate error message.
89 PL $4L E0amp+e 1<!1K =)+e> c21<?1K!,@+ 98 CREATE OR REPLACE TR&..ER $ecureEmp+oyee -E=ORE DELETE OR &/$ERT OR UPDATE O/ emp+oyee -E.&/ &= (TO_CEAR($B$DATE, JdayJ" &/ (J,aturdayJ, J,undayJ"" OR (TO_CEAR($B$DATE, J22 M>m)J" /OT -ETHEE/ JIL><IJ A/D J1L><IJ" TEE/ RA&$E_APPL&CAT&O/_ERROR(? IFII, JEmp+oyee ta*+e ), ,ecuredJ"3 E/D &=3 E/D3 8

'n attempt to update a ro& in the employee table is illustrated b# this !L statement. Oracle responds b# raising the specified error. )f #ou create and test the Secure%mployee trigger% "eep in mind that it &ill onl# fire if #ou execute a triggering event during one of the times specified for securing the table.
$4L> UPDATE Emp+oyee $ET $a+ary G 1I HEERE Emp+oyee&D G JI1LLFJ3 1evised+ 11(23(45 13 ( 22

Chapter 13

UPDATE Emp+oyee $ET $a+ary G 1I HEERE Emp+oyee&D G JI1LLFJ 9 ERROR at +)ne 1> ORA? IFII> Emp+oyee ta*+e ), ,ecured ORA?INF1 > at SD-OCQ!$ECUREE;PLOBEES, +)ne M ORA?IMILL> error dur)nC e0ecut)on o6 tr)CCer JD-OCQ!$ECUREE;PLOBEEJ

-", $rigger )xample $hile a 1O$ trigger fires once for ever# ro& processed b# the triggering statement% #ou can access data on the ro& currentl# being processed b# using t&o correlation identifiers named +old and +ne&. These are special Oracle bind variables. The PL/ !L compiler treats these t&o records as records of t#pe triggerOTableO0ameM1O$T?PA. These are "no&n as pseudo records as the# are not actual records in the database. To reference a column in the triggering table% use the notation sho&n here &here the ,olumn*ame value is a valid column in the triggering table.
>ne7!Co+umn/ame >o+d!Co+umn/ame

Table 13.3 summari/es the values of +old and +ne& pseudo records. Table 13.3 DML Statement )0 A1T <P:'TA :ALATA .old <ndefined , all column values are 0<LL as there is no EoldF version of the data ro& being inserted. tores the original values for the ro& being updated before the update ta"es place. tores the original values for the ro& being deleted before the deletion ta"es place. .new tores the values that &ill be inserted into the ne& ro& for the table. tores the ne& values for the ro& , values the ro& &ill contain after the update ta"es place. <ndefined , all column values are 0<LL as there &ill not be a Ene&F version of the ro& being deleted.

PL/ !L Axample 13.13 creates a table named e)uipment$audit. This table &ill store ro&s that create an audit trail of modifications made to the corresponding e*uipment table. The e)uipment$audit table has a column named Action to store information about the EactionF ta"en against the e*uipment table% for example% an )0 A1T% <P:'TA(OL:% <P:'TA(0A$% or :ALATA. ' second column named Action+ate defaults to the s#stem date and is used to log the date/time the table modification occurs.
89 PL $4L E0amp+e 1<!1L =)+e> c21<?1L!,@+ 98 CREATE TA-LE E@u)pment_Aud)t ( Act)on (ARCEAR (1I", Act)onDate DATE DE=AULT $B$DATE, E@u)pment/um*er CEAR(M", De,cr)pt)on (ARCEAR ( F", 1evised+ 11(23(45 13 ( 23

Chapter 13

Or)C)na+Co,t /U;-ER(K, ", 4uant)tyA:a)+a*+e /U;-ER(M", ProDect/um*er /U;-ER(M""3

PL/ !L Axample 13.1Q creates a ro& trigger that fires '.TA1 deleting% inserting% or updating an e)uipment table ro&K further% the trigger fires .O1 A'CH 1O$. This particular trigger creates an audit trail for modifications made to the table b# &riting ne& ro&s to the e)uipment$audit table.
89 PL $4L E0amp+e 1<!1O =)+e> c21<?1O!,@+ 98 CREATE OR REPLACE TR&..ER Aud)tE@u)pment A=TER DELETE OR &/$ERT OR UPDATE O/ E@u)pment =OR EACE ROH -E.&/ &= DELET&/. TEE/ &/$ERT &/TO e@u)pment_aud)t (ALUE$ (JDELETEJ, $B$DATE, >o+d!E@u)pment/um*er, >o+d!De,cr)pt)on, >o+d!Or)C)na+Co,t, >o+d!4uant)tyA:a)+a*+e, >o+d!ProDect/um*er"3 EL$&= &/$ERT&/. TEE/ &/$ERT &/TO e@u)pment_aud)t (ALUE$ (J&/$ERTJ, $B$DATE, >ne7!E@u)pment/um*er, >ne7!De,cr)pt)on, >ne7!Or)C)na+Co,t, >ne7!4uant)tyA:a)+a*+e, >ne7!ProDect/um*er"3 EL$E ?? updat)nC ?? &n,ert a *e6ore and a6ter )maCe o6 update, &/$ERT &/TO e@u)pment_aud)t (ALUE$ (JUPDATE?OLDJ, $B$DATE, >o+d!E@u)pment/um*er, >o+d!De,cr)pt)on, >o+d!Or)C)na+Co,t, >o+d!4uant)tyA:a)+a*+e, >o+d!ProDect/um*er"3 &/$ERT &/TO e@u)pment_aud)t (ALUE$ (JUPDATE?/EHJ, $B$DATE, >ne7!E@u)pment/um*er, >ne7!De,cr)pt)on, >ne7!Or)C)na+Co,t, >ne7!4uant)tyA:a)+a*+e, >ne7!ProDect/um*er"3 E/D &=3 E/D3 8

There are three trigger predicates that can be used to determine if a trigger is responding to a specific :;L statement+ )0 A1T)0D% <P:'T)0D% and :ALAT)0D. 0otice that PL/ !L Axample 13.1Q uses t&o of these in the ).(AL ).(AL A structure. These predicates return T1<A if the triggering statement is of the t#pe specifiedK other&ise% the# return .'L A. The script in PL/ !L Axample 13.24 tests the Audit%)uipment trigger. The script inserts a ne& e*uipment ro& for an @(1a# Table% and then modifies the ro& b# increasing the *uantit# available from 1 to 2 units. .inall#% the ro& is deleted. Aach :;L statement in the script fires the Audit%)uipment trigger. The output of the ALACT statement is listed after the script. This sho&s that four ne& ro&s &ere added to the e)uipment$audit table+ one ro& for the )0 A1T statement% t&o ro&s for the <P:'TA statement =a before and after image>% and 1 ro& for the :ALATA statement.
89 PL $4L E0amp+e 1<! I =)+e> c21<? I!,@+ 98 ?? &n,ert ne7 e@u)pment ro7 &/$ERT &/TO E@u)pment (ALUE$(JOIIIJ, J1?Ray Ta*+eJ, 1FFII!II, 1, L"3 CO;;&T3 1evised+ 11(23(45 13 ( 2J

Chapter 13

?? ;od)6y e@u)pment ro7 UPDATE E@u)pment $ET 4uant)tyA:a)+a*+e G JOIIIJ3 CO;;&T3

HEERE E@u)pment/um*er G

?? De+ete e@u)pment ro7 DELETE =RO; E@u)pment HEERE E@u)pment/um*er G JOIIIJ3 CO;;&T3 ?? L),t ro7, )n E@u)pment_Aud)t ta*+e! $ELECT 9 =RO; E@u)pment_Aud)t3 ACT&O/ ACT&O/DAT E4U& DE$CR&PT&O/ ?????????? ????????? ???? ???????????? &/$ERT F?/O(?IK OIII 1?Ray Ta*+e UPDATE?OLD F?/O(?IK OIII 1?Ray Ta*+e UPDATE?/EH F?/O(?IK OIII 1?Ray Ta*+e DELETE F?/O(?IK OIII 1?Ray Ta*+e OR&.&/ALCO$T ???????????? 1FFII 1FFII 1FFII 1FFII 4UA/ ???? 1 1 PROT ???? L L L L

,/)! Clause The $HA0 clause onl# applies to 1O$ triggers. The bod# of the trigger executes onl# &hen the condition specified is met. PL/ !L Axample 13.21 provides a partial outline for the logic of a trigger that includes a $HA0 clause. This example chec"s the value of the cost of a ne& item of e*uipment to be stored in the e*uipment table. )f the cost is too high% the action in the trigger bod# ta"es place. 0ote the seemingl# inconsistent use of the +ne& bind variable in the $HA0 clause. The s#ntax here is correct , #ou do not specif# the colon as part of the reference to the pseudo column.
89 PL $4L E0amp+e 1<! 1 98 CREATE OR REPLACE TR&..ER E)C2Co,t -E=ORE &/$ERT OR UPDATE O= Or)C)na+Co,t O/ e@u)pment =OR EACE ROH HEE/ (ne7!Or)C)na+Co,t > 1FIII" -E.&/ 89 Tr)CCer *ody act)on ), coded 2ere 98 /ULL3 E/D3 8

)na&ling and Disa&ling $riggers )t is useful to be able to enable and disable triggers. .or example% if #ou need to run a script that does a bul" load of the e)uipment table% #ou ma# not &ant to generate audit trail information regarding the bul" load. Having a tableBs triggers fire can seriousl# degrade the performance of a bul" load operation. 'n enabled trigger executes the trigger bod# if the triggering statement is issued. -# default% triggers are enabled. ' disabled trigger does not execute the trigger bod# even if the triggering statement is issued. The s#ntax for enabling and disabling triggers is+
?? D),a*+e an )nd):)dua+ tr)CCer *y name! ALTER TR&..ER tr)CCer_name D&$A-LE3 ?? D),a*+e a++ tr)CCer, a,,oc)ated 7)t2 a ta*+e! 1evised+ 11(23(45 13 ( 2L

Chapter 13

ALTER TA-LE ta*+e_name D&$A-LE ALL TR&..ER$3 ?? Ena*+e a tr)CCer t2at 7a, d),a*+ed! ALTER TR&..ER tr)CCer_name E/A-LE3 ?? Ena*+e a++ tr)CCer, a,,oc)ated 7)t2 a ta*+e! ALTER TA-LE ta*+e_name E/A-LE ALL TR&..ER$3

Dropping a $rigger The :1OP T1)DDA1 statement drops a trigger from the database. 'lso% if #ou drop a table% all associated table triggers are also dropped. The s#ntax is+
DROP TR&..ER tr)CCer_name3

SUMMAR )n this chapter #ou learned to &or" &ith subprograms including named procedures and functions% create pac"ages% and create triggers. Aach of these object t#pes is created b# &riting PL/ !L bloc"s. Pac"ages enable #ou to group PL/ !L t#pes% variables% exceptions% and subprograms that are logicall# related. Pac"ages ma"e it easier to develop applications. Procedures and functions are ver# flexible named database objects that compile &hen first executed% and thereafter provide ver# fast performance for completing a tas". -oth procedures and functions enable #ou to develop database objects that can interface &ith an application program. 'pplication program calls to procedures and functions ensure that database manipulation and exception(handling are securel# handled b# the application programming interface defined through the parameters associated &ith procedures and functions. :atabase triggers provide the abilit# to manage complex business rules% establish special audit trails% and derive column values automaticall#. Triggers are useful for replicating tables and logging events transparentl#. ?ou learned to create both T'TA;A0T and 1O$ triggers and used triggers for a common database processing tas"% creating an audit trail to trac" changes made to the data stored in a table. 0o& #ou are prepared to practice #our ne& s"ills b# completing the end of chapter revie& exercises. REVIE! E"ERCISES Learn $hese $erms 1. ProcedureUnamed PL/ !L bloc"s. 2. .unctionsUsimilar to a procedure% except that &hen a function is called% it returns a single value that is assigned to a variable. 3. )0Ua parameter t#pe for a parameter passed to a procedure as a read(onl# value that cannot be changed &ithin a procedure. J. O<TUa parameter t#pe for a parameter that receives a return value from a procedure. The value of this parameter can onl# appear on the left side of an assignment statement in the procedure.
1evised+ 11(23(45 13 ( 2N

Chapter 13

L. )0 O<TUa parameter t#pe that combines the )0 and O<T parameter t#pes. The parameter value is passed to a procedure% and its value can be changed &ithin a procedure. N. Pac"age bod#Ucontains the code for the subprograms declared in the pac"age specification. 5. Pac"age specificationUalso called the pac"age header% it is used to declare global variables% cursors% procedures% and functions that can be called or accessed b# other program units. 3. TriggerUa PL/ !L code bloc" attached and executed b# an event% &hich occurs to a database table. Q. 1o& TriggerUa trigger that fires once for each ro& that is affected b# a triggering statement. 14. tatement TriggerUa trigger that fires onl# once for a triggering statementK thus% a statement trigger fires once% regardless of the number of ro&s affected b# the triggering statement. Concepts Qui0 1. $hat is the distinguishing characteristic that ma"es functions different from proceduresR =chec" all that appl#> a. .unctions re*uire a P1'D;' 1A T1)CT clause. b. .unctions onl# ta"e )0 parameters. c. .unctions are stored in the database. d. .unctions re*uire a return value. e. 0one of the above. 2. $hat statement=s> &ill cause control to return to the calling environment in a functionR a. The raising of an exception. b. The initiali/ation of an O<T parameter. c. $riting to a database table. d. The 1AT<10 statement. e. 0one of the above. 3. )f a procedure has an )0 parameter% then it must have an O<T parameter. a. True b. .alse J. )f a function declares a user(defined exception but never explicitl# raises the exception% &hich of the follo&ing is trueR a. The function &ill not be able to compile. b. The function &ill fail a parit# level chec". c. The exception &ill never be raised. d. 's long as the exception has a 1AT<10 clause% there is no error in having a user( defined exception and not calling it. L. )0 O<T parameters are permissible in functions. a. True b. .alse c. The function &ill compile &ith an )0 O<T parameter% but it is not advisable to use them.

1evised+ 11(23(45

13 ( 25

Chapter 13

N. 'ssume a trigger named mytrigger alread# exists in the database. )f #ou use the C1A'TA clause to create a trigger &ith the same name because #ou need to modif# the existing trigger% &hat error message is generatedR Axplain #our ans&er. $hat approach should #ou ta"e insteadR 5. 'll procedures and functions in a pac"age bod# must be declared in the pac"age specification. a. True b. .alse 3. The main advantages to grouping procedures and functions into pac"ages are as follo&s =chec" all that appl#>+ a. )t follo&s the trend# object method of programming. b. )t is a more efficient &a# of utili/ing the processor memor#. c. )t ma"es greater use of the securit# privileges of various users. d. )t is a more efficient method to maximi/e tablespace storage. e. )t "eeps #ou on good terms &ith the :-'. Q. ' pac"age specification is merel# a formalit# for other programmers to let them "no& &hat parameters are being passed in and out of the procedures and functions. )t hides the program logic but in actualit# it is not necessar# and is incorporated into the pac"age bod#. a. True b. .alse 14. ' trigger can fire for &hich of the follo&ingR a. -efore a triggering event. b. 'fter a triggering event. c. -efore or after a triggering event. d. )nstead of a triggering event. 11. Ho& man# times does a ro& trigger fire if a :;L statement =)0 A1T% <P:'TA% or :ALATA> is issued against a tableR a. 's man# times as there are ro&s affected b# the :;L operation. b. Once per :;L operation. c. Once for ever# ro& of the table regardless of &hether the ro& is affected. 12. Ho& man# times does a statement trigger fire if a :;L =)0 A1T% <P:'TA% or :ALATA> operation is issued against a tableR a. 's man# times as there are ro&s affected b# the :;L operation. b. Once per :;L operation. c. Once for ever# ro& of the table regardless of &hether the ro& is affected.

1evised+ 11(23(45

13 ( 23

Chapter 13

PL/SQL Coding )xercises and Questions )n ans&ering the PL/ !L exercises and *uestions% submit a cop# of each script that #ou &rite along &ith an# messages that Oracle generates &hile executing #our program code. 'lso list the output for an# result table that is generated b# #our !L statements. 1. Create a function named #ncreaseSalary that ta"es t&o parameters% %mployee#+ and the percentage b# &hich a salaried emplo#ee needs their salar# needs to be raised. The function should return ne& salar# value from the employee table. 2. Create a procedure named =et uantity that has one )0 and one O<T parameter. This procedure should ta"e in the A*uipment0umber =of the e)uipment table> and return the uantityA&ailable *uantit# value for this e*uipment item b# use of the O<T parameter. 3. Create a procedure named %mployee+epartment &ith one )0 and one O<T parameter. This procedure should ta"e in the %mployee#+ column value and return the +epartment*ame column value of the department to &hich the emplo#ee is assigned. The procedure uses the employee and department tables. J. $rite a trigger that chec"s the value of the uantityA&ailable column of the e*uipment table for ever# update% and displa#s an error message if the uantityA&ailable falls belo& 2. L. $rite a trigger that fires before an update of the employee table for each ro& and chec"s if the ne& alar# column value is belo& 24444 =onl# for salar# &or"ers>. )f the salar# is lo&% &rite an error message to a log table. ?ou &ill need to create an appropriate log table for this exercise. N. $rite a trigger on the prescription table that fires after deleting a ro&% and stores the information about this department into a ne& table named prescription$audit. The prescription$audit table should have the same structure as the prescription table &ith one additional column named +el+ate that &ill store the date a prescription is deleted. 5. Create a pac"age that has one procedure% one function% and one exception. The procedure should ta"e as an )0 parameter a value for the %mployee#+ and return the emplo#ee name =concatenate the !ast*ame and :irst*ame columns> and department number values. The function should ta"e as an )0 parameter a value for the emplo#eeBs SS* column and a percentage b# &hich the emplo#eeBs >ageRate column value is to be raised. )f the SS* is not for a &age emplo#ee% then raise an appropriate exception. The function should return the ne& &age rate. 3. Create a procedure that &ill determine the %mployee#+ of the dept manager for an emplo#ee. The procedure should ta"e as an )0 parameter a value for the %mployee#+ for the emplo#ee that is supervised emplo#ee and return the %mployee#+ of the department manager. 1eturn a value of (1 if no department manager can be found. Q. Aach salaried emplo#ee is to be classified according to their salar#. Create a function to return the salar# class for an emplo#ee given the emplo#eeBs %mployee#+ value as an )0 parameter. The classification scheme is as follo&s+ Class '+ SW 14%444 Class -+ I 14%444 and SW 24%444 Class C+ I 24%444 14. 'ssuming each department is granted PL%444 to purchase an e*uipment item% create a function that can be called in order to determine if a ne& ro& can be added to the e)uipment
1evised+ 11(23(45 13 ( 2Q

Chapter 13

table. )n other &ords% create a -oolean function that ta"es the %)uipment*umber% Original-rice% and uantityA&ailable as parameters% and returns a T1<A if the total value =price times *uantit#> does not exceed the allo&anceK other&ise% return .'L A. 11. Create a trigger to ensure that ne& emplo#ees do not have a +ate?ired column value for their employee table ro& that begins on a aturda# and unda#. 12. Create a trigger that &ill limit project assignments to J projects for a single emplo#ee. )f there is an attempt to assign an emplo#ee to more than four projects =b# adding a ne& ro& to the projectAssignment table>% the trigger should displa# an error message instead of allo&ing the )0 A1T statement to process. 13. Create t&o tables named !ong9ermAssignment and S/ort9ermAssignment% both &ith the follo&ing columns+
Column 0ame EmployeeID ProjectNumber ?ours>or;ed +ate(pdated :ata t#pe CH'1 0<;-A1 0<;-A1 :'TA i/e L J =L%1> Comments Primary 1ey2 Amplo#ee identifier. 'lso Composite 'oreign 1ey lin" to employee table Primary 1ey2 Project number. 'lso Composite 'oreign 1ey lin" to project table. 0umber of hours an emplo#ee has &or"ed on a project. Primary 1ey. :ate &hen this ro& is changed.

Create a trigger that &ill fire for an )0 A1T to the projectAssignment table such that &hen column values for ?ours>or;ed e*uals the column value for -lanned?ours% the project assignment is completed. )f the ?ours>or;ed or -lanned?ours is 0<LL% the trigger should displa# an appropriate message and stop processing the data ro&. )f the ?ours>or;ed exceeds 144 hours% insert a ne& record to !ong9ermAssignment =long term assignment histor#>. )f the ?ours>or;ed is less than or e*ual to 144 hours% insert a ne& record to S/ort9ermAssignment. 1J. Create a procedure that calculates the total value for the -lanned?ours column across all project assignments for an emplo#ee given his or her %mployee#+ value.

1evised+ 11(23(45

13 ( 34

Vous aimerez peut-être aussi