Sei sulla pagina 1di 13

Chapter 20

DATABASE TRIGGERS

What is a database trigger? Types of Triggers Creating a database trigger Correlation names Instead-of triggers Knowing which command fired the trigger Enabling and disabling trigger Dropping a trigger

What is a Database Trigger?


Database trigger is a PL !"L bloc# that is e$ec%ted on an e&ent in the database' The e&ent is related to a partic%lar data manip%lation of a table s%ch as inserting( deleting or %pdating a row of a table'

Triggers may be used for any of the following:

To implement comple$ b%siness r%le( which cannot be implemented %sing To a%dit the process' )or e$ample( to #eep trac# of changes made to a table' To a%tomatically perform an action when another concerned action ta#es

integrity constraints'

place' )or e$ample( %pdating a table whene&er there is an insertion or a row into another table'

Triggers are similar to stored proced%res( b%t stored proced%res are called e$plicitly and triggers are called implicitly by *racle when the concerned e&ent occ%rs' Note: Triggers are automatically executed by Oracle and their execution is transparent to users.

Types of Triggers
Depending %pon( when a trigger is fired( it may be classified as +

!tatement-le&el trigger ,ow-le&el trigger -efore triggers .fter triggers

Statement-level Triggers
. statement trigger is fired only for once for a D/L statement irrespecti&e of the n%mber of rows affected by the statement' )or e$ample( if yo% e$ec%te the following 0PD.TE command !T0DE1T! table( statement trigger for 0PD.TE is e$ec%ted only for once' update students set where bcode = b2; bcode=b3

2owe&er( statements triggers cannot be %sed to access the data that is being inserted( %pdated or deleted' In other words( they do not ha&e access to #eywords 1EW and *LD( which are %sed to access data' !tatement-le&el triggers are typically %sed to enforce r%les that are not related to data' )or e$ample( it is possible to implement a r%le that says 3no body can modify -.TC2E! table after 4 P'/5' !tatement-le&el trigger is the defa%lt type of trigger'

Row-level Trigger
. row trigger is fired once for each row that is affected by D/L command' )or e$ample( if an 0PD.TE command %pdates 677 rows then row-le&el trigger is fired 677 times whereas a statement-le&el trigger is fired only for once' ,ow-le&el trigger are %sed to chec# for the &alidity of the data' They are typically %sed to implement r%les that cannot be implemented by integrity constraints' ,ow-le&el triggers are implemented by %sing the option )*, E.C2 ,*W in C,E.TE T,I88E, statement'

Before Triggers
While defining a trigger( yo% can specify whether the trigger is to be fired before the command 9I1!E,T( DELETE( and 0PD.TE: is e$ec%ted or after the command is e$ec%ted'

-efore triggers are commonly %sed to chec# the &alidity of the data before the action is performed' )or instance( yo% can %se before trigger to pre&ent deletion of row if deletion sho%ld not be allowed in the gi&en case'

A T!R Triggers
.fter triggers are fired after the triggering action is completed' )or e$ample( If after trigger is associated with I1!E,T command then it is fired after the row is inserted into the table'

"ossible Combinations
The following are the &ario%s possible combinations of database triggers'

-efore !tatement -efore ,ow .fter !tatement .fter ,ow

Note: Each of the above triggers can be associated with INSE T! "E#ETE! and $%"&TE commands resulting in a total of '( triggers. In the ne$t section( we will see how to create database triggers'

Creating a Database Trigger


C,E.TE T,I88E, command is %sed to create a database trigger' The following details are to be gi&en at the time of creating a trigger'

1ame of the trigger Table to be associated with When trigger is to be fired - before or after Command that in&o#es the trigger - 0PD.TE( DELETE( or I1!E,T Whether row-le&el trigger or not Condition to filter rows' PL !"L bloc# that is to be e$ec%ted when trigger is fired'

The following is the synta$ of C,E.TE T,I88E, command'

CREATE [OR REPLACE] TR !!ER tr"#erna$e %&E'ORE ( A'TER) %*ELETE ( +,ERT ( -P*ATE [O' co.u$ns]) [OR %*ELETE ( +,ERT (-P*ATE [O' co.u$ns])]/// O+ tab.e
3

['OR EAC0 RO1 [10E+ cond"t"on]] [RE'ERE+C +! [OL* A, o.d] [+E1 A, new]] PL2,3L b.oc4

Figure 1: E$ec%tion se;%ence of database triggers'

If FOR EACH ROW option is used then it becomes a ro !"e#e" tri$$er other ise it is a statement!"e#e" tri$$er%
WHEN is %sed to fire the trigger only when the gi&en condition is satisfied' This cla%se can be %sed only with row triggers' )or e$ample( the following trigger is fired only when ./*01T is more than 6777' create or rep.ace tr"##er // be5ore "nsert on pa6$ents 5or each row when 7new/a$ount 8 9::: OF option allows yo% to specify %pdation of which col%mns will fire trigger' The list of col%mns can be gi&en by separating col%mn by comma' REFERENCING is %sed to %se new names instead of defa%lt correlation names *LD and 1EW' !ee the section 3Correlation 1ames 3 The following is a simple database trigger that is %sed to chec# whether date of <oining of the st%dent is less than or e;%al to system date' *therwise it raises an error' create or rep.ace tr"##er students;b";row be5ore "nsert on students 5or each row be#"n "5 7new/d< 8 s6sdate then ra"se;app."cat"on;error =>2:::2?@*ate o5 <o"n"n# cannot be a5ter s6ste$ date/@A; end "5; end; !T0DE1T!=-I=,*W is the name of the trigger' It represents table name > !T0DE1T!( e&ent of the trigger > -I 9before insert: and type > ,*W' Tho%gh trigger name can be anything( it is better yo% follow a con&ention while naming it' )*, E.C2 ,*W specifies that this trigger is a row-le&el trigger' Condition +1EW'D? @ !A!D.TE chec#s whether the &al%e of D? of the row being inserted is greater than system date' If the condition is tr%e then it raises an error %sing ,.I!E=.PPLIC.TI*1=E,,*, proced%re'

Note: $se data dictionary view $SE )T I**E S to list the existing triggers.

&

The following command can be %sed to display the name and body of each trigger in the c%rrent acco%nt' se.ect tr"##er;na$e? tr"##er;bod6 5ro$ user;tr"##er; Col%mn T,I88E,=-*DA is of L*18 type' 2ow many characters of this col%mn will be displayed is determined by &ariable L*18 in !"LBPl%s' !et &ariable L*18 to a larger &al%e to see the complete body of the trigger' The defa%lt &al%e of L*18 is C7'

The following is another trigger %sed to implement a r%le that cannot be implemented by integrity constraints' The trigger chec#s whether payment made by the st%dent is more than what the st%dent is s%pposed to pay' create or rep.ace tr"##er pa6$ents;b";row be5ore "nsert on pa6$ents 5or each row dec.are B;duea$t nu$ber=CA; be#"n B;duea$t 7= #etduea$t=7new/ro..noA; "5 7new/a$ount 8 B;duea$t then ra"se;app."cat"on;error=>2:992?@A$ount be"n# pa"d "s $ore than what "s to be pa"d@A; end "5; end; The abo&e trigger ma#es %se of 8ETD0E./T f%nction that we created in the pre&io%s chapter' It first gets the d%e amo%nt of the gi&en roll n%mber' If the amo%nt being paid > &al%es of ./*01T col%mn > is more than the d%e amo%nt then trigger fails'

Statement-level trigger e#ample


The following is an e$ample of statement-le&el trigger' .s we ha&e seen in the pre&io%s section( a statement trigger is fired only for once for the entire statement irrespecti&e of the n%mber of rows affected by the statement' create or rep.ace tr"##er pa6$ents;b"ud be5ore "nsert or update or de.ete on pa6$ents be#"n "5 to;char=s6sdate?@*D@A = @,-+@ then ra"se;app."cat"on;error=>2:999?@+o chan#es can be $ade on sunda6/@A; end "5; end;

'

The abo&e trigger is fired whene&er an 0PD.TE or DELETE or I1!E,T command is e$ec%ted on P.A/E1T! table' Trigger chec#s whether day of wee# of the system date is !%nday' If condition is tr%e then it raises an application error' !ince the trigger is not concerned with data( it %ses a statement-le&el trigger'

$ali% Statements in trigger bo%y


The following are the only &alid statements in trigger body' Trigger can ma#e %se of e$isting stored proced%res( f%nctions and pac#ages 9as shown in the pre&io%s e$ample:'

D/L commands !ELECT I1T* command

Correlation &ames
The defa%lt correlation names are 1EW for new &al%es and *LD for old &al%es of the row' !o( in order to access the &al%es of new row %se 1EW and to access the &al%es of old 9e$isting: row( %se *LD' It is also possible to change these correlation names %sing ,E)E,E1CI18 option of C,E.TE T,I88E, command' This is done mainly to a&oid names conflicts between table names and correlation names' !ee the table 6( to %nderstand the a&ailability of correlation name with triggering commands' Command (E)E*E I1!E,T 0PD.TE NEW 1o Aes Aes OLD Aes 1o Aes

Table 1+ .&ailability of correlation names 1EW is not a&ailable with DELETE command beca%se there are no new &al%es' In the same way( *LD is not a&ailable with I1!E,T beca%se a new row is being inserted and it doesnDt contain old &al%es' Triggers based on 0PD.TE command can access both 1EW and *LD correlation names' *LD refers to &al%es that refer to &al%es before the change and 1EW refers to &al%es that are after the change' The following trigger pre&ents any change to ./*01T col%mn of P.A/E1T! table' This is done by comparing old &al%e with new &al%e and if they differ that means the &al%e is changed and trigger fails' create or rep.ace tr"##er pa6$ents;bu;row be5ore update

on pa6$ents 5or each row be#"n "5 7new/a$ount E8 7o.d/a$ount then ra"se;app."cat"on;error=>2:993?@A$ount cannot be chan#ed/ P.ease de.ete and re"nsert the row? "5 reFu"red@A; end "5; end;

'nstea%-of Trigger
These trigger are defined on relation-&iews and ob<ect-&iews' These triggers are %sed to modify &iews that cannot be directly modified by D/L commands' 0nli#e normal trigger( which are fired d%ring the e$ec%tion of D/L commands( these triggers are fired instead of e$ec%tion of D/L commands' That means instead of e$ec%ting D/L command on the &iew( *racle in&o#es the corresponding I1!TE.D-*) trigger' The following is a &iew based on !T0DE1T! and P.A/E1T! tables' create B"ew newstudent as se.ect s/ro..no? na$e? bcode?#ender? a$ount 5ro$ students s? pa6$ents p where s/ro..no = p/ro..no;

5 6ou tr6 to "nsert data "nto +E1,T-*E+T tab.e then Orac.e d"sp.a6s the 5o..ow"n# error/ ,3L8 "nsert "nto newstudent Ba.ues =9C?@Goe@?@b2@?@$@?2:::A; "nsert "nto newstudent Ba.ues =9C?@Goe@?@b2@?@$@?2:::A H ERROR at ."ne 97 ORA>:9IIJ7 cannot $od"56 a co.u$n wh"ch $aps to a non 4e6>preserBed tab.e -%t( we want the data s%pplied to 1EW!T0DE1T &iew to be inserted into !T0DE1T! and P.A/E1T! table' This can be done with an instead of trigger as follows+ create or rep.ace tr"##er newstudent;"t;b";row "nstead o5 "nsert on newstudent 5or each row be#"n >> "nsert "nto ,T-*E+T, tab.e 5"rst "nsert "nto students=ro..no?bcode?na$e?#ender?d<A Ba.ues=7new/ro..no? 7new/bcode? 7new/na$e? 7new/#ender?s6sdateA; >> "nsert a row "nto PADKE+T, tab.e "nsert "nto pa6$ents

Ba.ues=7new/ro..no? s6sdate? 7new/a$ountA; end; The abo&e I1!TE.D-*) trigger is %sed to insert one row into !T0DE1T! table with roll n%mber( name( batch code and gender of the st%dent' It then inserts a row into P.A/E1T! table with roll n%mber( date of payment - sysdate( and amo%nt' !ince we created an I1!TE.D-*) trigger for I1!E,T command( *racle in&o#es this trigger when an I1!E,T command is e$ec%ted on 1EW!T0DE1T! &iew' ,3L8 "nsert "nto newstudent Ba.ues =9C?@Goe@?@b2@?@$@?2:::A; !o the abo&e command inserts two rows > one into !T0DE1T! table and another into P.A/E1T! table' The following two ;%eries will ratify that' se.ect ro..no? bcode?na$e? #ender? d< 5ro$ students where ro..no = 9C; ROLL+O &CO*E +AKE ! *G >>>>>>>>> >>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > >>>>>>>>> 9C b2 Goe $ 3:>Oct>:9

se.ect H 5ro$ pa6$ents where ro..no = 9C; ROLL+O *P AKO-+T >>>>>>>>> >>>>>>>>> >>>>>>>>> 9C 3:>OCT>:9 2:::

(nowing whi)h )omman% fire% the trigger


When a trigger may be fired by more than one D/L command( it may be re;%ired to #now which D/L command act%ally fired the trigger' 0se the following conditional predicates in the body of the trigger to chec# which command fired the trigger'

I1!E,TI18 DELETI18 0PD.TI18

The following e$ample is %sed to log information abo%t the change made to table C*0,!E!' The trigger ma#es %se of a C*0,!E!=L*8 table( which is created with the following str%ct%re' create tab.e courses;.o#

1-

c$d p4 dc un

nu$ber=9A? Barchar2=2:A? date? Barchar2=2:A

A;

Now a row level trigger is used to insert a row into COURSES_LOG table whenever there is a change to COURSES table.
create or rep.ace tr"##er courses;b"ud;row be5ore "nsert or de.ete or update on courses 5or each row be#"n "5 "nsert"n# then "nsert "nto courses;.o# Ba.ues =9? 7new/ccode?s6sdate? userA; e.s"5 de.et"n# then "nsert "nto courses;.o# Ba.ues=2?7o.d/ccode?s6sdate?userA; e.se "nsert "nto courses;.o# Ba.ues=3?7o.d/ccode?s6sdate?userA; end "5; end; .fter the trigger is created( if yo% e$ec%te an 0PD.TE command as follows+ update courses set 5ee = 5ee H 9/9 where ccode = @ora@; it will fire C*0,!E!=-I0D=,*W trigger( which will insert a row into C*0,!E!=L*8 table as follows+ ,3L8 se.ect H 5ro$ courses;.o#; CK* PL *C -+ >>>>>>>>> >>>>>>>>>>>>>>>>>>>> >>>>>>>>> >>>>>>>>>>>>>>>>>>>> 3 ora 3:>OCT>:9 &OOL

!nabling an% %isabling triggers


. database trigger may be either in enabled state or disabled state' Disabling trigger my impro&e performance when a large amo%nt of table data is to be modified( beca%se the trigger code is not e$ec%ted' )or e$ample( -P*ATE students set na$e = upper=na$eA; will r%n faster if all the triggers fired by 0PD.TE on !T0DE1T! table are disabled' 0se .LTE, T,I88E, command to enable or disable triggers as follows+

11

a.ter tr"##er

pa6$ents;bu;row d"sab.e;

. disabled trigger is not fired %ntil it is enabled' 0se the following command to enable a disabled trigger' a.ter tr"##er pa6$ents;bu;row enab.e; The following command disables all triggers of !T0DE1T! table' a.ter tab.e students d"sab.e a.. tr"##ers;

Dropping a Trigger
When a trigger is no longer needed it can be dropped %sing D,*P T,I88E, command as follows' drop tr"##er pa6$ents;bu;row;

S*mmary
Database triggers are %sed to implement comple$ b%siness r%les that cannot be implemented %sing integrity constraints' Triggers can also be %sed for logging and to ta#e actions that sho%ld be a%tomatically performed' Trigger may be fired before the D/L operation or after D/L operation' Trigger may be fired for each row affected by the D/L operation or for the entire statement' I1!TE.D-*) trigger are called instead of e$ec%ting the gi&en D/L command' They are defined on relational-&iews and ob<ect-&iews 9will be disc%ssed later in this boo#:' . trigger can be disabled to increase the performance when a lot of data manip%lations are to be done on the table'

!#er)ises
6' E' F' G' J' Which data dictionary &iew contains information abo%t triggers?============== 2ow many before trigger can we create?========= Is it possible to create two or more trigger for the same e&ent9-E)*,E I1!E,T:? =====' What is the defa%lt type of trigger?H!tatement rowI=== Create a trigger to pre&ent any changes to )EE col%mn of C*0,!E! table in s%ch a way that increase is more than the half of the e$isting co%rse fee'

12

K'

Create a trigger to pre&ent all deletions between 4p'm to 4 a'm'

13

Potrebbero piacerti anche