Top Banner

of 32

Week5 Triggers

May 29, 2018

Download

Documents

Asif Amin
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/8/2019 Week5 Triggers

    1/32

    Week 5Week 5

    Triggers

  • 8/8/2019 Week5 Triggers

    2/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT2

    In this lecture, you will learn:

    Introduction toTriggers Partsofa Trigger

    TypesofTriggers

    TriggerExecution ExampleofTriggerUses

    Viewing Trigger Information in the Data

    Dictionary

  • 8/8/2019 Week5 Triggers

    3/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT3

    Readings

    RequiredReadings Oracle Database Concepts:

    Chapter22 Triggers

    Oracle Database Application Developer's Guide -

    Fundamentals Chapter9 CodingTriggers

    FurtherReadings

    Oracle Database PL/SQL User's Guide and

    Reference Oracle Database SQL Reference

  • 8/8/2019 Week5 Triggers

    4/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT 4

    Triggers

    Trigger: a PL/SQL unit implicitlyfired by Oraclewhen atriggeringevent occurs.

    Youcan write triggers that firewheneveroneof the

    followingoperationsoccurs,

    DML statements (INSERT, UPDATE, DELETE) on a particular

    tableorview,issued by anyuser

    DDL statements (CREATE orALTERprimarily) issuedeitherby

    a particularschema/userorby anyschema/userin thedatabase

    Databaseevents,such aslogon/logoff,errors,or

    startup/shutdown, alsoissued

  • 8/8/2019 Week5 Triggers

    5/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT5

    Firing Triggers

    Figure 22-1 Triggersin Oracledocumentation

  • 8/8/2019 Week5 Triggers

    6/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT 6

    How Triggers Are Used

    Automaticallygeneratederivedcolumn values Prevent invalid transactions

    Enforcecomplex security authorizations

    Enforcereferentialintegrity across nodesin adistributeddatabase

    Enforcecomplex businessrules

    Providetransparent event logging

  • 8/8/2019 Week5 Triggers

    7/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT 7

    How Triggers Are Used

    Provideauditing Maintain synchronous tablereplicates

    Gatherstatisticson table access

    Modify tabledata when DML statements areissued against views

    Publish information about databaseevents,user

    events, and SQL statements tosubscribing

    applications

  • 8/8/2019 Week5 Triggers

    8/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT 8

    A Simple Trigger

    Thefollowingstatement creates a triggerforthe Emp_tab table:

    CREATE OR REPLACE TRIGGERPrint_salary_changes

    BEFORE DELETE OR INSERT OR UPDATE ON Emp_tabFOR EACH ROW

    WHEN (new.Empno > 0)DECLAREsal_diff number;

    BEGINsal_diff := :new.sal - :old.sal;

    dbms_output.put('Old salary: ' || :old.sal);dbms_output.put(' New salary: ' || :new.sal);dbms_output.put_line(' Difference ' || sal_diff);

    END;/

  • 8/8/2019 Week5 Triggers

    9/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT 9

    Parts of a Trigger

    A trigger has three basicparts: A triggeringevent orstatement

    A triggerrestriction

    A trigger action

    Figure 22-3 The

    REORDERTriggerinOracledocumentation

  • 8/8/2019 Week5 Triggers

    10/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT 10

    Triggering Event or Statement

    A triggeringevent orstatement is the SQL statement,databaseevent,oruserevent that causes a trigger to

    fire. A triggeringevent can beoneormoreof the

    following:

    An INSERT, UPDATE,orDELETE statement on a specific table

    (orview,in somecases)

    A CREATE, ALTER,orDROP statement on anyschema object

    A databasestartuporinstanceshutdown

    A specificerrormessageoranyerrormessage

    A userlogon orlogoff

    Forexample:... UPDATE OF parts_on_hand ON inventory ...

  • 8/8/2019 Week5 Triggers

    11/32

    CP2503/5503 Entreprise Database System - Oracle J

    CU-SM

    PIT 11

    Trigger Restriction

    A triggerrestriction specifies a Booleanexpression that must be trueforthe trigger to

    fire.

    The triggeraction will not run if the trigger

    restriction evaluates tofalseorunknown.

    In theexample, the triggerrestriction is:

    new.parts_on_hand < new.reorder_point

    The triggerdoes not fireunless the numberofavailablepartsis

    less than a preset orderamount

  • 8/8/2019 Week5 Triggers

    12/32

    CP

    2503/5503 Entreprise Database System - Oracle JCU

    -SMPIT 1

    2

    Trigger Action

    A trigger action is theprocedure (PL/SQL block,Java program,orC callout) that contains theSQL statements andcode to berun when thefollowingeventsoccur: A triggeringstatement isissued

    The triggerrestriction evaluates totrue

    Likestoredprocedures, a trigger action can: Contain SQL, PL/SQL,orJava statements

    Define PL/SQL languageconstructssuch asvariables,constants,cursors,exceptions

    Define Java languageconstructs

    Callstoredprocedures

  • 8/8/2019 Week5 Triggers

    13/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 13

    Designing Triggers

    Limit thesizeofthe trigger action to no morethan 60 lines (~35Kbytes)

    ifmorecodingis needed,placeinside a stored

    procedure, then create a trigger that calls the

    procedure

    Becarefulofrecursive triggers

    a recursivetriggerthat fires after theupdateofEMP

    table,which the triggeritselfalsoissue an update tothe EMP table.

    it willloopuntilout ofmemory

  • 8/8/2019 Week5 Triggers

    14/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 14

    Designing Triggers

    Becarefulofcascading triggers Excessiveuseoftriggerscan result in complex

    interdependencies

    Thiscan bedifficult to maintain in a large application

    a recursivetriggerthat fires after theupdateofEMPcascadingtrigger causingchain fireoftriggers

    Cascading triggerscan causeunintendedresults

    Difficult tounderstand

    Couldresult in a recursive triggercall

  • 8/8/2019 Week5 Triggers

    15/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 15

    Cascading Triggers

    Figure 22-2

    Cascading

    Triggersin

    Oracle

    documentation

  • 8/8/2019 Week5 Triggers

    16/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 16

    Triggers Compared with DeclarativeIntegrity Constraints

    Youcan use both triggers andintegrityconstraints todefine andenforce any typeofintegrityrule

    However,onlyuse triggers toconstrain data input in the

    followingsituations: Toenforcereferentialintegritywhen thechild andparent tables

    areon different nodesofa distributeddatabase

    Toenforcecomplex businessrules not definableusingintegrity

    constraints

    When a requiredreferentialintegrityrulecannot beenforcedusing thefollowingintegrityconstraints:

    NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK,

    DELETE CASCADE, DELETE SET NULL

  • 8/8/2019 Week5 Triggers

    17/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 17

    Types ofTriggers

    RowTriggers and Statement Triggers BEFORE and AFTERTriggers

    INSTEAD OF Triggers

    Triggerson System Events and UserEvents

  • 8/8/2019 Week5 Triggers

    18/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 18

    Row Triggers and Statement Triggers

    When youdefine a trigger,youcan specify thenumberoftimes the trigger action is to berun:

    Onceforeveryrow affected by the triggering

    statement,such as a triggerfired by an UPDATEstatement that updates manyrows

    Oncefor the triggeringstatement, no matterhow

    manyrowsit affects

  • 8/8/2019 Week5 Triggers

    19/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 19

    Row Triggers and Statement Triggers

    RowTriggers (BEFORE /AFTER)

    triggerfiresonceforeach row affected by thetriggeringstatement

    e.g., an updatestatement updates manyrowsin atablewillfire the trigger many times

    R

    ow triggers areusefulif thecodein the triggeraction dependson data provided by thetriggeringstatement orrows that are affected bythe triggeringstatement

  • 8/8/2019 Week5 Triggers

    20/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 20

    Row Triggers and Statement Triggers

    Statement Triggers (BEFORE /AFTER) triggerfiresonceforeach triggeringstatement,

    regardlessof the numberofrows affected,even ifnorows are affected

    e.g., a deletestatement deleteseveralrowsfrom a

    table, a statement level DELETE triggerwillfireonlyonce

    Statement triggers areusefulif thecodein thetriggeraction does not dependon data provided

    by the triggeringstatement orrows affected: Make a complex securitycheck on thecurrent timeor

    user

    Generate a single audit record

  • 8/8/2019 Week5 Triggers

    21/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 21

    BEFORE and AFTER Triggers

    When defining a trigger,youcan specify thetriggertiming

    BEFOREtriggersrun the triggeraction before

    the triggeringstatement isrun:

    When the trigger action determineswhether the

    triggershould be allowed tocomplete

    Toderivespecificcolumn values beforecompleting a

    triggering INSERTorUPDATE statement

    AFTER triggersrun the triggeraction afterthe

    triggeringstatement isrun

  • 8/8/2019 Week5 Triggers

    22/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 22

    INSTEAD ofTriggers

    When you need toexecute DML on a non-updateableview,you need tocreate an INSTEAD of trigger

    The triggerwill beexecuted,insteadofthe triggeringstatement

    Modifyingviewscan have ambiguousresults

    Deleting a rowin a viewcouldeithermean deletingit from the

    base tableor

    updatingsomevaluesso that it is nolongerselected by theview

    Inserting a rowin a viewcouldeithermean inserting a newrow

    into the base table

    orupdating an existingrowso that it isprojected by theview

    Updating a column in a view that involves joins might thesemanticsof

    othercolumns that are not projected by theview

  • 8/8/2019 Week5 Triggers

    23/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 23

    Triggers on System Events and User Events

    System events Databasestartup andshutdown

    Data Guardrole transitions

    Servererrormessageevents

    Userevents

    Userlogon andlogoff

    DML statements (INSERT, DELETE, & UPDATE)

    DDL statements (CREATE, ALTER, & DROP)

  • 8/8/2019 Week5 Triggers

    24/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 24

    Triggers on System Events and User Events

    Triggerson system eventscan bedefined at thedatabaselevelorschema level

    CREATE OR REPLACE TRIGGER On_Logon

    AFTER LOGONON The_user.Schema

    BEGINDo_Something;

    END;

  • 8/8/2019 Week5 Triggers

    25/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 25

    Enabling and Disabling Triggers

    You might temporarilydisable a triggerif: an object the triggerreferencesis not available

    you need toperform a largedata load, andyouwant it toproceed

    quicklywithout firing triggers

    you arereloadingdata

    ALTER TRIGGER trigger_name ENABLE;

    ALTER TRIGGER trigger_name DISABLE;

    ALTER TABLE table_name ENABLE ALL

    TRIGGERS;

    ALTER TABLE table_name DISABLE ALL

    TRIGGERS;

  • 8/8/2019 Week5 Triggers

    26/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 26

    The Execution Model for Triggers andIntegrity Constraint Checking

    A single SQL statement can potentiallyfireup tofourtypesoftriggers:

    BEFORE statement trigger

    BEFORE row trigger

    AFTERstatement trigger

    AFTERrow trigger

  • 8/8/2019 Week5 Triggers

    27/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 27

    The Execution Model for Triggers andIntegrity Constraint Checking

    BEFOR

    E statement trigger Beforeexecuting the triggeringstatement, the triggeraction is

    run

    BEFORE row trigger Before modifyingeach row affected by the triggeringstatement

    and beforechecking appropriateintegrityconstraints, the triggeraction isrun,ifthe triggerrestriction is not violated

    AFTERstatement trigger Afterexecuting the triggeringstatement and applying any

    deferredintegrityconstraints, the triggeraction isrun

    AFTERrow trigger Aftermodifyingeach row affected by the triggeringstatement and

    possibly applying appropriateintegrityconstraints, the triggeraction isrun forthecurrent rowprovided the triggerrestrictionwas not violated. AFTERrow triggerslock rows

  • 8/8/2019 Week5 Triggers

    28/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 28

    Execution Model for Triggers

    1.Run allBEFORE statement triggers that apply to thestatement.

    2.Loopforeach row affected by the SQL statement.

    a.Run allBEFORE row triggers that apply to thestatement.

    b.Lock andchangerow, andperform integrityconstraint

    checking. (Thelock is not releaseduntil the transaction iscommitted.)

    c.Run allAFTERrow triggers that apply to thestatement.

    3.Completedeferredintegrityconstraint checking.

    4.Run allAFTERstatement triggers that apply to thestatement.

    What willhappenifthere aremultiplebeforestatementtriggerstriggered by

    thesame DML statement?

  • 8/8/2019 Week5 Triggers

    29/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 29

    Triggers Information

    Thefollowing Data Dictionaryviews haveinformation about triggers: USER_TRIGGERS

    ALL_TRIGGERS

    DBA_TRIGGERS

    SELECT Trigger_type, Triggering_event, Table_nameFROM USER_TRIGGERS

    WHERE Trigger_name = 'REORDER';

    TYPE TRIGGERING_STATEMENT TABLE_NAME------------ -------------------- --------

    AFTER EACH ROW UPDATE INVERTORY

    SELECT Trigger_body

    FROM USER_TRIGGERSWHERE Trigger_name = 'REORDER';

  • 8/8/2019 Week5 Triggers

    30/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 30

    Trigger Example (Source codes provided inreadings)

    Auditing

    Integrity

    Complex Check

    Complex Security

    Transparent Logging

    Tracking System Events

  • 8/8/2019 Week5 Triggers

    31/32

    CP 2503/5503 Entreprise Database System - Oracle JCU-SMPIT 31

    Revision Questions

    What is a trigger? What are thedifferences between row triggers

    andstatement triggers?

    What is an insteadoftrigger?

    Which Data Dictionaryviews haveinformationabout a trigger?

    How triggers areused?

    Howis the triggerexecution modelin Oracle

    work? How tocreate,enable anddisable triggers?

    When we maydisable triggers?

  • 8/8/2019 Week5 Triggers

    32/32

    End of Week 5End of Week 5