Sie sind auf Seite 1von 17

9/30/2015

Triggers

SkipHeaders
Oracle9iDatabaseConcepts
Release2(9.2)
PartNumberA9652401

Home Book Contents Index Master Feedback


List
Index

17
Triggers
Thischapterdiscussestriggers,whichareprocedureswritteninPL/SQL,Java,orCthatrun(fire)
implicitlywheneveratableorviewismodifiedorwhensomeuseractionsordatabasesystemactions
occur.Youcanwritetriggersthatfirewheneveroneofthefollowingoperationsoccurs:DMLstatements
onaparticularschemaobject,DDLstatementsissuedwithinaschemaordatabase,userlogonorlogoff
events,servererrors,databasestartup,orinstanceshutdown.
Thischapterincludes:
IntroductiontoTriggers
PartsofaTrigger
TypesofTriggers
TriggerExecution

IntroductiontoTriggers
OracleletsyoudefineprocedurescalledtriggersthatrunimplicitlywhenanINSERT,UPDATE,orDELETE
statementisissuedagainsttheassociatedtableor,insomecases,againstaview,orwhendatabase
systemactionsoccur.TheseprocedurescanbewritteninPL/SQLorJavaandstoredinthedatabase,or
theycanbewrittenasCcallouts.
Triggersaresimilartostoredprocedures.AtriggerstoredinthedatabasecanincludeSQLandPL/SQL
orJavastatementstorunasaunitandcaninvokestoredprocedures.However,proceduresandtriggers
differinthewaythattheyareinvoked.Aprocedureisexplicitlyrunbyauser,application,ortrigger.
TriggersareimplicitlyfiredbyOraclewhenatriggeringeventoccurs,nomatterwhichuserisconnected
orwhichapplicationisbeingused.
Figure171showsadatabaseapplicationwithsomeSQLstatementsthatimplicitlyfireseveraltriggers
storedinthedatabase.Noticethatthedatabasestorestriggersseparatelyfromtheirassociatedtables.
Figure171Triggers

http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

1/17

9/30/2015

Triggers

Textdescriptionoftheillustrationcncpt076.gif
AtriggercanalsocallouttoaCprocedure,whichisusefulforcomputationallyintensiveoperations.
Theeventsthatfireatriggerincludethefollowing:
DMLstatementsthatmodifydatainatable(INSERT,UPDATE,orDELETE)
DDLstatements
Systemeventssuchasstartup,shutdown,anderrormessages
Usereventssuchaslogonandlogoff
Note:
OracleFormscandefine,store,andruntriggersofadifferentsort.However,
donotconfuseOracleFormstriggerswiththetriggersdiscussedinthis
chapter.
SeeAlso:
Chapter14,"SQL,PL/SQL,andJava"forinformationonthesimilarities
oftriggerstostoredprocedures
"TheTriggeringEventorStatement"

HowTriggersAreUsed
TriggerssupplementthestandardcapabilitiesofOracletoprovideahighlycustomizeddatabase
managementsystem.Forexample,atriggercanrestrictDMLoperationsagainstatabletothoseissued
duringregularbusinesshours.Youcanalsousetriggersto:
Automaticallygeneratederivedcolumnvalues
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

2/17

9/30/2015

Triggers

Preventinvalidtransactions
Enforcecomplexsecurityauthorizations
Enforcereferentialintegrityacrossnodesinadistributeddatabase
Enforcecomplexbusinessrules
Providetransparenteventlogging
Provideauditing
Maintainsynchronoustablereplicates
Gatherstatisticsontableaccess
ModifytabledatawhenDMLstatementsareissuedagainstviews
Publishinformationaboutdatabaseevents,userevents,andSQLstatementstosubscribing
applications
SeeAlso:
Oracle9iApplicationDeveloper'sGuideFundamentalsforexamplesof
triggeruses
SomeCautionaryNotesaboutTriggers
Althoughtriggersareusefulforcustomizingadatabase,usethemonlywhennecessary.Excessiveuseof
triggerscanresultincomplexinterdependencies,whichcanbedifficulttomaintaininalargeapplication.
Forexample,whenatriggerfires,aSQLstatementwithinitstriggeractionpotentiallycanfireother
triggers,resultingincascadingtriggers.Thiscanproduceunintendedeffects.Figure172illustrates
cascadingtriggers.
Figure172CascadingTriggers

http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

3/17

9/30/2015

Triggers

Textdescriptionoftheillustrationcncpt077.gif
TriggersComparedwithDeclarativeIntegrityConstraints
Youcanusebothtriggersandintegrityconstraintstodefineandenforceanytypeofintegrityrule.
However,OracleCorporationstronglyrecommendsthatyouusetriggerstoconstraindatainputonlyin
thefollowingsituations:
Toenforcereferentialintegritywhenchildandparenttablesareondifferentnodesofadistributed
database
Toenforcecomplexbusinessrulesnotdefinableusingintegrityconstraints
Whenarequiredreferentialintegrityrulecannotbeenforcedusingthefollowingintegrity
constraints:
NOTNULL,UNIQUE
PRIMARYKEY
FOREIGNKEY
CHECK
DELETECASCADE
DELETESETNULL
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

4/17

9/30/2015

Triggers

SeeAlso:
"HowOracleEnforcesDataIntegrity"formoreinformationabout
integrityconstraints

PartsofaTrigger
Atriggerhasthreebasicparts:
Atriggeringeventorstatement
Atriggerrestriction
Atriggeraction
Figure173representseachofthesepartsofatriggerandisnotmeanttoshowexactsyntax.The
sectionsthatfollowexplaineachpartofatriggeringreaterdetail.
Figure173TheREORDERTrigger

Textdescriptionoftheillustrationcncpt078.gif

TheTriggeringEventorStatement
AtriggeringeventorstatementistheSQLstatement,databaseevent,orusereventthatcausesatrigger
tofire.Atriggeringeventcanbeoneormoreofthefollowing:
AnINSERT,UPDATE,orDELETEstatementonaspecifictable(orview,insomecases)
ACREATE,ALTER,orDROPstatementonanyschemaobject
Adatabasestartuporinstanceshutdown
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

5/17

9/30/2015

Triggers

Aspecificerrormessageoranyerrormessage
Auserlogonorlogoff
Forexample,inFigure173,thetriggeringstatementis:
...UPDATEOFparts_on_handONinventory...

Thisstatementmeansthatwhentheparts_on_handcolumnofarowintheinventorytableisupdated,
firethetrigger.WhenthetriggeringeventisanUPDATEstatement,youcanincludeacolumnlistto
identifywhichcolumnsmustbeupdatedtofirethetrigger.YoucannotspecifyacolumnlistforINSERT
andDELETEstatements,becausetheyaffectentirerowsofinformation.
AtriggeringeventcanspecifymultipleSQLstatements:
...INSERTORUPDATEORDELETEOFinventory...

ThispartmeansthatwhenanINSERT,UPDATE,orDELETEstatementisissuedagainsttheinventorytable,
firethetrigger.WhenmultipletypesofSQLstatementscanfireatrigger,youcanuseconditional
predicatestodetectthetypeoftriggeringstatement.Inthisway,youcancreateasingletriggerthatruns
differentcodebasedonthetypeofstatementthatfiresthetrigger.

TriggerRestriction
AtriggerrestrictionspecifiesaBooleanexpressionthatmustbetrueforthetriggertofire.Thetrigger
actionisnotrunifthetriggerrestrictionevaluatestofalseorunknown.Intheexample,thetrigger
restrictionis:
new.parts_on_hand<new.reorder_point

Consequently,thetriggerdoesnotfireunlessthenumberofavailablepartsislessthanapresentreorder
amount.

TriggerAction
Atriggeractionistheprocedure(PL/SQLblock,Javaprogram,orCcallout)thatcontainstheSQL
statementsandcodetoberunwhenthefollowingeventsoccur:
Atriggeringstatementisissued.
Thetriggerrestrictionevaluatestotrue.
Likestoredprocedures,atriggeractioncan:
ContainSQL,PL/SQL,orJavastatements
DefinePL/SQLlanguageconstructssuchasvariables,constants,cursors,exceptions
DefineJavalanguageconstructs
Callstoredprocedures
Ifthetriggersarerowtriggers,thestatementsinatriggeractionhaveaccesstocolumnvaluesoftherow
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

6/17

9/30/2015

Triggers

beingprocessedbythetrigger.Correlationnamesprovideaccesstotheoldandnewvaluesforeach
column.

TypesofTriggers
Thissectiondescribesthedifferenttypesoftriggers:
RowTriggersandStatementTriggers
BEFOREandAFTERTriggers
INSTEADOFTriggers
TriggersonSystemEventsandUserEvents

RowTriggersandStatementTriggers
Whenyoudefineatrigger,youcanspecifythenumberoftimesthetriggeractionistoberun:
Onceforeveryrowaffectedbythetriggeringstatement,suchasatriggerfiredbyanUPDATE
statementthatupdatesmanyrows
Onceforthetriggeringstatement,nomatterhowmanyrowsitaffects
RowTriggers
Arowtriggerisfiredeachtimethetableisaffectedbythetriggeringstatement.Forexample,ifan
UPDATEstatementupdatesmultiplerowsofatable,arowtriggerisfiredonceforeachrowaffectedbythe
UPDATEstatement.Ifatriggeringstatementaffectsnorows,arowtriggerisnotrun.
Rowtriggersareusefulifthecodeinthetriggeractiondependsondataprovidedbythetriggering
statementorrowsthatareaffected.Forexample,Figure173illustratesarowtriggerthatusesthevalues
ofeachrowaffectedbythetriggeringstatement.
StatementTriggers
Astatementtriggerisfiredonceonbehalfofthetriggeringstatement,regardlessofthenumberofrows
inthetablethatthetriggeringstatementaffects,evenifnorowsareaffected.Forexample,ifaDELETE
statementdeletesseveralrowsfromatable,astatementlevelDELETEtriggerisfiredonlyonce.
Statementtriggersareusefulifthecodeinthetriggeractiondoesnotdependonthedataprovidedbythe
triggeringstatementortherowsaffected.Forexample,useastatementtriggerto:
Makeacomplexsecuritycheckonthecurrenttimeoruser
Generateasingleauditrecord

BEFOREandAFTERTriggers
Whendefiningatrigger,youcanspecifythetriggertimingwhetherthetriggeractionistoberun
beforeorafterthetriggeringstatement.BEFOREandAFTERapplytobothstatementandrowtriggers.
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

7/17

9/30/2015

Triggers

BEFOREandAFTERtriggersfiredbyDMLstatementscanbedefinedonlyontables,notonviews.
However,triggersonthebasetablesofaviewarefiredifanINSERT,UPDATE,orDELETEstatementisissued
againsttheview.BEFOREandAFTERtriggersfiredbyDDLstatementscanbedefinedonlyonthedatabase

oraschema,notonparticulartables.
SeeAlso:
"INSTEADOFTriggers"
"TriggersonSystemEventsandUserEvents"forinformationabouthow
BEFOREandAFTERtriggerscanbeusedtopublishinformationaboutDMLand
DDLstatements
BEFORETriggers
BEFOREtriggersrunthetriggeractionbeforethetriggeringstatementisrun.Thistypeoftriggeris

commonlyusedinthefollowingsituations:
Whenthetriggeractiondetermineswhetherthetriggeringstatementshouldbeallowedto
complete.UsingaBEFOREtriggerforthispurpose,youcaneliminateunnecessaryprocessingofthe
triggeringstatementanditseventualrollbackincaseswhereanexceptionisraisedinthetrigger
action.
ToderivespecificcolumnvaluesbeforecompletingatriggeringINSERTorUPDATEstatement.
AFTERTriggers
AFTERtriggersrunthetriggeractionafterthetriggeringstatementisrun.

TriggerTypeCombinations
Usingtheoptionslistedpreviously,youcancreatefourtypesofrowandstatementtriggers:
BEFOREstatementtrigger
Beforeexecutingthetriggeringstatement,thetriggeractionisrun.
BEFORErowtrigger
Beforemodifyingeachrowaffectedbythetriggeringstatementandbeforecheckingappropriate
integrityconstraints,thetriggeractionisrun,ifthetriggerrestrictionwasnotviolated.
AFTERrowtrigger
Aftermodifyingeachrowaffectedbythetriggeringstatementandpossiblyapplyingappropriate
integrityconstraints,thetriggeractionisrunforthecurrentrowprovidedthetriggerrestriction
wasnotviolated.UnlikeBEFORErowtriggers,AFTERrowtriggerslockrows.
AFTERstatementtrigger
Afterexecutingthetriggeringstatementandapplyinganydeferredintegrityconstraints,thetrigger
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

8/17

9/30/2015

Triggers

actionisrun.
Youcanhavemultipletriggersofthesametypeforthesamestatementforanygiventable.Forexample,
youcanhavetwoBEFOREstatementtriggersforUPDATEstatementsontheemployeestable.Multiple
triggersofthesametypepermitmodularinstallationofapplicationsthathavetriggersonthesametables.
Also,OraclematerializedviewlogsuseAFTERrowtriggers,soyoucandesignyourownAFTERrowtrigger
inadditiontotheOracledefinedAFTERrowtrigger.
YoucancreateasmanytriggersoftheprecedingdifferenttypesasyouneedforeachtypeofDML
statement,(INSERT,UPDATE,orDELETE).
Forexample,supposeyouhaveatable,SAL,andyouwanttoknowwhenthetableisbeingaccessedand
thetypesofqueriesbeingissued.Thefollowingexamplecontainsasamplepackageandtriggerthat
tracksthisinformationbyhourandtypeofaction(forexample,UPDATE,DELETE,orINSERT)ontableSAL.
TheglobalsessionvariableSTAT.ROWCNTisinitializedtozerobyaBEFOREstatementtrigger.Thenitis
increasedeachtimetherowtriggerisrun.Finallythestatisticalinformationissavedinthetable
STAT_TABbytheAFTERstatementtrigger.
SeeAlso:
Oracle9iApplicationDeveloper'sGuideFundamentalsforexamplesoftrigger
applications

INSTEADOFTriggers
INSTEADOFtriggersprovideatransparentwayofmodifyingviewsthatcannotbemodifieddirectly
throughDMLstatements(INSERT,UPDATE,andDELETE).ThesetriggersarecalledINSTEADOFtriggers

because,unlikeothertypesoftriggers,Oraclefiresthetriggerinsteadofexecutingthetriggering
statement.
YoucanwritenormalINSERT,UPDATE,andDELETEstatementsagainsttheviewandtheINSTEADOFtrigger
isfiredtoupdatetheunderlyingtablesappropriately.INSTEADOFtriggersareactivatedforeachrowofthe
viewthatgetsmodified.
ModifyViews
Modifyingviewscanhaveambiguousresults:
Deletingarowinaviewcouldeithermeandeletingitfromthebasetableorupdatingsomevalues
sothatitisnolongerselectedbytheview.
Insertingarowinaviewcouldeithermeaninsertinganewrowintothebasetableorupdatingan
existingrowsothatitisprojectedbytheview.
Updatingacolumninaviewthatinvolvesjoinsmightchangethesemanticsofothercolumnsthat
arenotprojectedbytheview.
Objectviewspresentadditionalproblems.Forexample,akeyuseofobjectviewsistorepresent
master/detailrelationships.Thisoperationinevitablyinvolvesjoins,butmodifyingjoinsisinherently
ambiguous.
Asaresultoftheseambiguities,therearemanyrestrictionsonwhichviewsaremodifiable.AnINSTEAD
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

9/17

9/30/2015

Triggers

OFtriggercanbeusedonobjectviewsaswellasrelationalviewsthatarenototherwisemodifiable.

Eveniftheviewisinherentlymodifiable,youmightwanttoperformvalidationsonthevaluesbeing
inserted,updatedordeleted.INSTEADOFtriggerscanalsobeusedinthiscase.Herethetriggercode
performsthevalidationontherowsbeingmodifiedandifvalid,propagatethechangestotheunderlying
tables.
INSTEADOFtriggersalsoenableyoutomodifyobjectviewinstancesontheclientsidethroughOCI.To

modifyanobjectmaterializedbyanobjectviewintheclientsideobjectcacheandflushitbacktothe
persistentstore,youmustspecifyINSTEADOFtriggers,unlesstheobjectviewisinherentlymodifiable.
However,itisnotnecessarytodefinethesetriggersforjustpinningandreadingtheviewobjectinthe
objectcache.
SeeAlso:
Chapter13,"ObjectDatatypesandObjectViews"
OracleCallInterfaceProgrammer'sGuide
Oracle9iApplicationDeveloper'sGuideFundamentalsforanexampleofan
INSTEADOFtrigger
ViewsThatAreNotModifiable
Aviewisinherentlymodifiableifdatacanbeinserted,updated,ordeletedwithoutusingINSTEADOF
triggersandifitconformstotherestrictionslistedasfollows.Iftheviewquerycontainsanyofthe
followingconstructs,theviewisnotinherentlymodifiableandyouthereforecannotperforminserts,
updates,ordeletesontheview:
Setoperators
Aggregatefunctions
GROUPBY,CONNECTBY,orSTARTWITHclauses

TheDISTINCToperator
Joins(however,somejoinviewsareupdatable)
Ifaviewcontainspseudocolumnsorexpressions,youcanonlyupdatetheviewwithanUPDATEstatement
thatdoesnotrefertoanyofthepseudocolumnsorexpressions.
SeeAlso:
"UpdatableJoinViews"
INSTEADOFTriggersonNestedTables
YoucannotmodifytheelementsofanestedtablecolumninaviewdirectlywiththeTABLEclause.
However,youcandosobydefininganINSTEADOFtriggeronthenestedtablecolumnoftheview.The
triggersonthenestedtablesfireifanestedtableelementisupdated,inserted,ordeletedandhandlethe
actualmodificationstotheunderlyingtables.
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

10/17

9/30/2015

Triggers

SeeAlso:
Oracle9iApplicationDeveloper'sGuideFundamentals
Oracle9iSQLReferenceforinformationontheCREATETRIGGERstatement

TriggersonSystemEventsandUserEvents
Youcanusetriggerstopublishinformationaboutdatabaseeventstosubscribers.Applicationscan
subscribetodatabaseeventsjustastheysubscribetomessagesfromotherapplications.Thesedatabase
eventscaninclude:
Systemevents
Databasestartupandshutdown
Servererrormessageevents
Userevents
Userlogonandlogoff
DDLstatements(CREATE,ALTER,andDROP)
DMLstatements(INSERT,DELETE,andUPDATE)
Triggersonsystemeventscanbedefinedatthedatabaselevelorschemalevel.Forexample,adatabase
shutdowntriggerisdefinedatthedatabaselevel:
CREATETRIGGERregister_shutdown
ONDATABASE
SHUTDOWN
BEGIN
...
DBMS_AQ.ENQUEUE(...);
...
END;

TriggersonDDLstatementsorlogon/logoffeventscanalsobedefinedatthedatabaselevelorschema
level.TriggersonDMLstatementscanbedefinedonatableorview.Atriggerdefinedatthedatabase
levelfiresforallusers,andatriggerdefinedattheschemaortablelevelfiresonlywhenthetriggering
eventinvolvesthatschemaortable.
EventPublication
EventpublicationusesthepublishsubscribemechanismofOracleAdvancedQueuing.Aqueueserves
asamessagerepositoryforsubjectsofinteresttovarioussubscribers.TriggersusetheDBMS_AQpackage
toenqueueamessagewhenspecificsystemorusereventsoccur.
SeeAlso:
Oracle9iApplicationDeveloper'sGuideAdvancedQueuing
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

11/17

9/30/2015

Triggers

Oracle9iSuppliedPL/SQLPackagesandTypesReference
EventAttributes
Eacheventallowstheuseofattributeswithinthetriggertext.Forexample,thedatabasestartupand
shutdowntriggershaveattributesfortheinstancenumberandthedatabasename,andthelogonand
logofftriggershaveattributesfortheusername.Youcanspecifyafunctionwiththesamenameasan
attributewhenyoucreateatriggerifyouwanttopublishthatattributewhentheeventoccurs.The
attribute'svalueisthenpassedtothefunctionorpayloadwhenthetriggerfires.FortriggersonDML
statements,the:OLDcolumnvaluespasstheattribute'svaluetothe:NEWcolumnvalue.
SystemEvents
Systemeventsthatcanfiretriggersarerelatedtoinstancestartupandshutdownanderrormessages.
Triggerscreatedonstartupandshutdowneventshavetobeassociatedwiththedatabase.Triggers
createdonerroreventscanbeassociatedwiththedatabaseorwithaschema.
STARTUPtriggersfirewhenthedatabaseisopenedbyaninstance.Theirattributesincludethe

systemevent,instancenumber,anddatabasename.
SHUTDOWNtriggersfirejustbeforetheserverstartsshuttingdownaninstance.Youcanusethese

triggerstomakesubscribingapplicationsshutdowncompletelywhenthedatabaseshutsdown.For
abnormalinstanceshutdown,thesetriggerscannotbefired.TheattributesofSHUTDOWNtriggers
includethesystemevent,instancenumber,anddatabasename.
SERVERERRORtriggersfirewhenaspecifiederroroccurs,orwhenanyerroroccursifnoerror

numberisspecified.Theirattributesincludethesystemeventanderrornumber.
UserEvents
Usereventsthatcanfiretriggersarerelatedtouserlogonandlogoff,DDLstatements,andDML
statements.
TriggersonLOGONandLOGOFFEvents
LOGONandLOGOFFtriggerscanbeassociatedwiththedatabaseorwithaschema.Theirattributesinclude
thesystemeventandusername,andtheycanspecifysimpleconditionsonUSERIDandUSERNAME.
LOGONtriggersfireafterasuccessfullogonofauser.
LOGOFFtriggersfireatthestartofauserlogoff.

TriggersonDDLStatements

DDLtriggerscanbeassociatedwiththedatabaseorwithaschema.Theirattributesincludethesystem
event,thetypeofschemaobject,anditsname.Theycanspecifysimpleconditionsonthetypeandname
oftheschemaobject,aswellasfunctionslikeUSERIDandUSERNAME.DDLtriggersincludethefollowing
typesoftriggers:
BEFORECREATEandAFTERCREATEtriggersfirewhenaschemaobjectiscreatedinthedatabaseor
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

12/17

9/30/2015

Triggers

schema.
BEFOREALTERandAFTERALTERtriggersfirewhenaschemaobjectisalteredinthedatabaseor

schema.
BEFOREDROPandAFTERDROPtriggersfirewhenaschemaobjectisdroppedfromthedatabaseor

schema.
TriggersonDMLStatements

DMLtriggersforeventpublicationareassociatedwithatable.TheycanbeeitherBEFOREorAFTER
triggersthatfireforeachrowonwhichthespecifiedDMLoperationoccurs.YoucannotuseINSTEADOF
triggersonviewstopublisheventsrelatedtoDMLstatementsinstead,youcanpublisheventsusing
BEFOREorAFTERtriggersfortheDMLoperationsonaview'sunderlyingtablesthatarecausedbyINSTEAD
OFtriggers.
TheattributesofDMLtriggersforeventpublicationincludethesystemeventandthecolumnsdefined
bytheuserintheSELECTlist.Theycanspecifysimpleconditionsonthetypeandnameoftheschema
object,aswellasfunctions(suchasUID,USER,USERENV,andSYSDATE),pseudocolumns,andcolumns.The
columnscanbeprefixedby:OLDand:NEWforoldandnewvalues.TriggersonDMLstatementsinclude
thefollowingtriggers:
BEFOREINSERTandAFTERINSERTtriggersfireforeachrowinsertedintothetable.
BEFOREUPDATEandAFTERUPDATEtriggersfireforeachrowupdatedinthetable.
BEFOREDELETEandAFTERDELETEtriggersfireforeachrowdeletedfromthetable.

SeeAlso:
"RowTriggers"
"BEFOREandAFTERTriggers"
Oracle9iApplicationDeveloper'sGuideFundamentalsformore
informationabouteventpublicationusingtriggersonsystemeventsand
userevents

TriggerExecution
Atriggerisineitheroftwodistinctmodes:
Trigger
Mode
Definition
Enabled

Anenabledtriggerrunsitstriggeractionifatriggeringstatementisissuedandthetrigger
restriction(ifany)evaluatestoTRUE.
Disabled Adisabledtriggerdoesnotrunitstriggeraction,evenifatriggeringstatementisissuedand
thetriggerrestriction(ifany)wouldevaluatetoTRUE.
Forenabledtriggers,Oracleautomaticallyperformsthefollowingactions:
Runstriggersofeachtypeinaplannedfiringsequencewhenmorethanonetriggerisfiredbya
singleSQLstatement
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

13/17

9/30/2015

Triggers

Performsintegrityconstraintcheckingatasetpointintimewithrespecttothedifferenttypesof
triggersandguaranteesthattriggerscannotcompromiseintegrityconstraints
Providesreadconsistentviewsforqueriesandconstraints
Managesthedependenciesamongtriggersandschemaobjectsreferencedinthecodeofthetrigger
action
Usestwophasecommitifatriggerupdatesremotetablesinadistributeddatabase
Firesmultipletriggersinanunspecifiedorder,ifmorethanonetriggerofthesametypeexistsfora
givenstatement

TheExecutionModelforTriggersandIntegrityConstraintChecking
AsingleSQLstatementcanpotentiallyfireuptofourtypesoftriggers:
BEFORErowtriggers
BEFOREstatementtriggers
AFTERrowtriggers
AFTERstatementtriggers

Atriggeringstatementorastatementwithinatriggercancauseoneormoreintegrityconstraintstobe
checked.Also,triggerscancontainstatementsthatcauseothertriggerstofire(cascadingtriggers).
Oracleusesthefollowingexecutionmodeltomaintaintheproperfiringsequenceofmultipletriggersand
constraintchecking:
1. RunallBEFOREstatementtriggersthatapplytothestatement.
2. LoopforeachrowaffectedbytheSQLstatement.
a. RunallBEFORErowtriggersthatapplytothestatement.
b. Lockandchangerow,andperformintegrityconstraintchecking.(Thelockisnotreleased
untilthetransactioniscommitted.)
c. RunallAFTERrowtriggersthatapplytothestatement.
3. Completedeferredintegrityconstraintchecking.
4. RunallAFTERstatementtriggersthatapplytothestatement.
Thedefinitionoftheexecutionmodelisrecursive.Forexample,agivenSQLstatementcancausea
BEFORErowtriggertobefiredandanintegrityconstrainttobechecked.ThatBEFORErowtrigger,inturn,
mightperformanupdatethatcausesanintegrityconstrainttobecheckedandanAFTERstatementtrigger
tobefired.TheAFTERstatementtriggercausesanintegrityconstrainttobechecked.Inthiscase,the
executionmodelrunsthestepsrecursively,asfollows:
OriginalSQLstatementissued.
1. BEFORErowtriggersfired.
a. AFTERstatementtriggersfiredbyUPDATEinBEFORErowtrigger.
i.StatementsofAFTERstatementtriggersrun.
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

14/17

9/30/2015

Triggers

ii.IntegrityconstraintcheckedontableschangedbyAFTERstatementtriggers.
b. StatementsofBEFORErowtriggersrun.
c. IntegrityconstraintcheckedontableschangedbyBEFORErowtriggers.
2. SQLstatementrun.
3. IntegrityconstraintfromSQLstatementchecked.
Therearetwoexceptionstothisrecursion:
Whenatriggeringstatementmodifiesonetableinareferentialconstraint(eithertheprimarykeyor
foreignkeytable),andatriggeredstatementmodifiestheother,onlythetriggeringstatementwill
checktheintegrityconstraint.Thisallowsrowtriggerstoenhancereferentialintegrity.
StatementtriggersfiredduetoDELETECASCADEandDELETESETNULLarefiredbeforeandafterthe
userDELETEstatement,notbeforeandaftertheindividualenforcementstatements.Thisprevents
thosestatementtriggersfromencounteringmutatingerrors.
AnimportantpropertyoftheexecutionmodelisthatallactionsandchecksdoneasaresultofaSQL
statementmustsucceed.Ifanexceptionisraisedwithinatrigger,andtheexceptionisnotexplicitly
handled,allactionsperformedasaresultoftheoriginalSQLstatement,includingtheactionsperformed
byfiredtriggers,arerolledback.Thus,integrityconstraintscannotbecompromisedbytriggers.The
executionmodeltakesintoaccountintegrityconstraintsanddisallowstriggersthatviolatedeclarative
integrityconstraints.
Forexample,inthepreviouslyoutlinedscenario,supposethatSteps1through8succeedhowever,in
Step9theintegrityconstraintisviolated.Asaresultofthisviolation,allchangesmadebytheSQL
statement(inStep8),thefiredBEFORErowtrigger(inStep6),andthefiredAFTERstatementtrigger(in
Step4)arerolledback.
Note:
Althoughtriggersofdifferenttypesarefiredinaspecificorder,triggersofthesame
typeforthesamestatementarenotguaranteedtofireinanyspecificorder.For
example,allBEFORErowtriggersforasingleUPDATEstatementmaynotalwaysfirein
thesameorder.Designyourapplicationssotheydonotrelyonthefiringorderof
multipletriggersofthesametype.

DataAccessforTriggers
Whenatriggerisfired,thetablesreferencedinthetriggeractionmightbecurrentlyundergoingchanges
bySQLstatementsinotherusers'transactions.Inallcases,theSQLstatementsrunwithintriggersfollow
thecommonrulesusedforstandaloneSQLstatements.Inparticular,ifanuncommittedtransactionhas
modifiedvaluesthatatriggerbeingfiredeitherneedstoread(query)orwrite(update),thentheSQL
statementsinthebodyofthetriggerbeingfiredusethefollowingguidelines:
Queriesseethecurrentreadconsistentmaterializedviewofreferencedtablesandanydata
changedwithinthesametransaction.
Updateswaitforexistingdatalockstobereleasedbeforeproceeding.
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

15/17

9/30/2015

Triggers

Thefollowingexamplesillustratethesepoints.
DataAccessforTriggersExample1

Assumethatthesalary_checktrigger(body)includesthefollowingSELECTstatement:
SELECTmin_salary,max_salaryINTOmin_salary,max_salary
FROMjobs
WHEREjob_title=:new.job_title;

Forthisexample,assumethattransactionT1includesanupdatetothemax_salarycolumnofthejobs
table.Atthispoint,thesalary_checktriggerisfiredbyastatementintransactionT2.TheSELECT
statementwithinthefiredtrigger(originatingfromT2)doesnotseetheupdatebytheuncommitted
transactionT1,andthequeryinthetriggerreturnstheoldmax_salaryvalueasofthereadconsistentpoint
fortransactionT2.
DataAccessforTriggersExample2

Assumethatthetotal_salarytriggermaintainsaderivedcolumnthatstoresthetotalsalaryofall
membersinadepartment:
CREATETRIGGERtotal_salary
AFTERDELETEORINSERTORUPDATEOFdepartment_id,salaryONemployees
FOREACHROWBEGIN
/*assumethatdepartment_idandsalaryarenonnullfields*/
IFDELETINGOR(UPDATINGAND:old.department_id!=:new.department_id)
THENUPDATEdepartments
SETtotal_salary=total_salary:old.salary
WHEREdepartment_id=:old.department_id;
ENDIF;
IFINSERTINGOR(UPDATINGAND:old.department_id!=:new.department_id)
THENUPDATEdepartments
SETtotal_salary=total_salary+:new.salary
WHEREdepartment_id=:new.department_id;
ENDIF;
IF(UPDATINGAND:old.department_id=:new.department_idAND
:old.salary!=:new.salary)
THENUPDATEdepartments
SETtotal_salary=total_salary:old.salary+:new.salary
WHEREdepartment_id=:new.department_id;
ENDIF;
END;

Forthisexample,supposethatoneuser'suncommittedtransactionincludesanupdatetothe
total_salarycolumnofarowinthedepartmentstable.Atthispoint,thetotal_salarytriggerisfiredby
aseconduser'sSQLstatement.Becausetheuncommittedtransactionofthefirstusercontainsanupdate
toapertinentvalueinthetotal_salarycolumn(thatis,arowlockisbeingheld),theupdatesperformed
bythetotal_salarytriggerarenotrununtilthetransactionholdingtherowlockiscommittedorrolled
back.Therefore,theseconduserwaitsuntilthecommitorrollbackpointofthefirstuser'stransaction.

StorageofPL/SQLTriggers
http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

16/17

9/30/2015

Triggers

OraclestoresPL/SQLtriggersincompiledform,justlikestoredprocedures.WhenaCREATETRIGGER
statementcommits,thecompiledPL/SQLcode,calledPcode(forpseudocode),isstoredinthedatabase
andthesourcecodeofthetriggerisflushedfromthesharedpool.
SeeAlso:
PL/SQLUser'sGuideandReferenceformoreinformationaboutcompilingand
storingPL/SQLcode

ExecutionofTriggers
Oraclerunsatriggerinternallyusingthesamestepsusedforprocedureexecution.Theonlysubtle
differenceisthatauserhastherighttofireatriggerifheorshehastheprivilegetorunthetriggering
statement.Otherthanthis,triggersarevalidatedandrunthesamewayasstoredprocedures.
SeeAlso:
PL/SQLUser'sGuideandReferenceformoreinformationaboutstoredprocedures

DependencyMaintenanceforTriggers
Likeprocedures,triggersdependonreferencedobjects.Oracleautomaticallymanagesthedependencies
ofatriggerontheschemaobjectsreferencedinitstriggeraction.Thedependencyissuesfortriggersare
thesameasthoseforstoredprocedures.Triggersaretreatedlikestoredprocedures.Theyareinserted
intothedatadictionary.
SeeAlso:
Chapter15,"DependenciesAmongSchemaObjects"
Copyright1996,2002OracleCorporation.
AllRightsReserved.

http://docs.oracle.com/cd/B10500_01/server.920/a96524/c18trigs.htm

Home Book Contents Index Master Feedback


List
Index

17/17

Das könnte Ihnen auch gefallen