2 Triggers

Embed Size (px)

Citation preview

  • 8/4/2019 2 Triggers

    1/20

    9/15/2011

    Triggers

    1

    IF-2305 Pemrograman Basis Data

    Tahun Ajaran 2011-2012

  • 8/4/2019 2 Triggers

    2/20

    9/15/2011

    Triggers

    Triggers is a procedure that is automatically invoked by the DBMSin response to specified changes to the database

    A trigger description contains three part:

    Event: A change to the database that activates the trigger

    The sorts of events allowed are usually insert, delete or

    2

    up ate to a part cu ar re at on Condition: A query or test that is run when the trigger is

    activated

    If the condition does not hold, then nothing else associated

    with the trigger happens in response to this event. Action: A procedure that is executed when the trigger is

    activated and its condition is true

    The action could be any sequence of database operations,

    perhaps even operations not connected in any way to thetriggering event

  • 8/4/2019 2 Triggers

    3/20

    9/15/2011

    Triggers vs Constraints

    Triggers are only awakened when certain events, specified by thedatabase programmer, occur.

    Instead of immediately preventing the event that awakened it, atrigger tests a condition.

    If the condition of the trigger is satisfied, theactionassociated with

    3

    .

  • 8/4/2019 2 Triggers

    4/20

    9/15/2011

    Principal Features

    The action may be executed either before or after the triggeringevent.

    The action can refer to both old and/or new values of tuples thatwere inserted, deleted, or updated in the event that triggered theaction.

    4

    attributes.

    A condition may be specified by a WHEN clause; the action isexecuted only if the rule is triggered and the condition holds whenthe triggering event occurs.

    The programmer has an option of specifying that the action isperformed either:

    Once for each modified tuple, or

    Once for all the tuples that are changed in one databaseoperation.

  • 8/4/2019 2 Triggers

    5/20

    9/15/2011

    Example

    CREATE TABLE T4 (a INTEGER, b CHAR(10));

    CREATE TABLE T5 (c CHAR(10), d INTEGER);

    CREATE TRIGGER trig1

    AFTER INSERT ON T4

    } declaration

    } event

    5

    REFERENCING NEW AS newRowFOR EACH ROW

    WHEN (newRow.a

  • 8/4/2019 2 Triggers

    6/20

    9/15/2011

    Trigger Layout

    BEFORE: the WHEN condition is tested before the triggeringevent, that is, before the modification that awakened the trigger

    has been made to the database

    If the condition is true, then the action of the trigger isexecuted.

    6

    ,whether the condition is true.

    AFTER: the action is executed after the triggering event

    The OF keyword: optional for UPDATE

    defines the event to be only an update of the attribute(s) listedafter the keyword OF

    The WHEN clause is optional.

    If it is missing, then the action is executed whenever the trigger

    is awakened.

  • 8/4/2019 2 Triggers

    7/20

    9/15/2011

    Trigger Layout

    Action surrounded by BEGIN.. .END and separated by semicolons

    FOR EACH ROW: row-level trigger

    executed once for each tuple

    FOR EACH STATEMENT: statement-level trigger

    executed once whenever a statement of the appropriate type

    7

    is executed no matter how many rows - zero, one, or many - itactually affects

  • 8/4/2019 2 Triggers

    8/20

    9/15/2011

    Trigger Syntax in Oracle

    CREATE [OR REPLACE] TRIGGER

    {BEFORE|AFTER} {INSERT|DELETE|UPDATE} ON

    [REFERENCING [NEW AS ] [OLD AS ]

    [FOR EACH ROW [WHEN ()]]

    8

    Basic triggers syntax in Oracle is differs slightly from standard

    SQL syntax

  • 8/4/2019 2 Triggers

    9/20

    9/15/2011

    Trigger Syntax in Oracle Basic triggers syntax in Oracle is differs slightly from standard

    SQL syntax

    Only for row-level triggers: The special variables NEW and OLD are available to refer to

    new and old tuples respectively. Note: In the trigger body,NEW and OLD must be preceded by a colon (":"), but in the

    9

    WHEN clause, they do not have a preceding colon! Seeexample below.

    The REFERENCING clause can be used to assign aliases tothe variables NEW and OLD.

    A trigger restriction can be specified in the WHEN clause,

    enclosed by parentheses. The trigger restriction is a SQLcondition that must be satisfied in order for Oracle to fire thetrigger. This condition cannot contain subqueries. Without theWHEN clause, the trigger is fired for each row.

  • 8/4/2019 2 Triggers

    10/20

    9/15/2011

    Trigger Syntax in Oracle The restrictions on include:

    You cannot modify the same relation whose modification is theevent triggering the trigger.

    You cannot modify a relation connected to the triggeringrelation by another constraint such as a foreign-key constraint.

    10

  • 8/4/2019 2 Triggers

    11/20

    9/15/2011

    ExampleSET SERVEROUTPUT ON

    CREATE TRIGGER CheckStar

    BEFORE INSERT ON StarsIn

    REFERENCING NEW AS newRow

    11

    FOR EACH ROWBEGIN

    INSERT INTO MovieStar(name) VALUES (:newRow.StarName);

    DBMS_OUTPUT.PUT_LINE('New Star '||:newRow.StarName||'!!');

    END CheckStar;

    What is the event, condition and action of this trigger?

    What does this trigger do?

  • 8/4/2019 2 Triggers

    12/20

    9/15/2011

    ExampleSET SERVEROUTPUT ON

    CREATE TRIGGER StudioProduct

    AFTER INSERT ON Movie

    DECLARE

    m_length NUMBER := 0;

    12

    BEGINSELECT SUM(length) INTO m_length FROM Movie;

    DBMS_OUTPUT.PUT_LINE('We have '|| m_length ||' minutes ofmovies!!');

    END StudioProduct;

    What is the event, condition and action of this trigger?

    What does this trigger do?

    What differentiate this trigger from the previous?

  • 8/4/2019 2 Triggers

    13/20

  • 8/4/2019 2 Triggers

    14/20

  • 8/4/2019 2 Triggers

    15/20

    9/15/2011

    Aborting Triggers with ErrorCREATE TABLE Person (age INT);

    CREATE TRIGGER PersonCheckAgeAFTER INSERT OR UPDATE OF age ON PersonFOR EACH ROW

    15

    IF (:new.age < 0) THENRAISE_APPLICATION_ERROR(-20000, 'no negative age

    allowed');END IF;

    END;.RUN;

  • 8/4/2019 2 Triggers

    16/20

    9/15/2011

    Aborting Triggers with Error If we attempted to execute the insertion:

    INSERT INTO Person VALUES (-3);

    we would get the error message:

    ERROR at line 1:

    16

    ORA-20000: no negative age allowedORA-06512: at "MYNAME.PERSONCHECKAGE", line 3ORA-04088: error during execution of trigger'MYNAME.PERSONCHECKAGE'

    and nothing would be inserted. In general, the effects of both thetrigger and the triggering statement are rolled back.

  • 8/4/2019 2 Triggers

    17/20

    9/15/2011

    Why Triggers Can Be Hard to Understand

    The DBMS always checks whether some trigger is activated bythe statement(s) that modifies the database

    If a statement activates more than one trigger, the DBMS typicallyprocesses all of them, in some arbitrary order

    The execution of the action part of a trigger could in turn activate

    17

    In particular, execution of the action part of a trigger couldagain activate the same trigger (recursive triggers)

  • 8/4/2019 2 Triggers

    18/20

    9/15/2011

    Recursive TriggersCREATE TRIGGER t1

    AFTER INSERT ON table1

    FOR EACH ROW

    BEGIN

    update_table_2();

    18

    CREATE TRIGGER t2

    AFTER UPDATE ON table2

    FOR EACH ROW

    BEGIN

    insert_into_table_1();

    END

  • 8/4/2019 2 Triggers

    19/20

    9/15/2011

    Constraints versus Triggers A constraint prevents the data from being made inconsistent by

    any kind of statement

    A trigger is activated by a special kind of statement (e.g., an insertor delete statement)

    Triggers allow us to maintain database integrity in more flexible

    19

  • 8/4/2019 2 Triggers

    20/20

    9/15/2011

    Other Uses of Triggers Triggers can alert users to unusual events (as reflected in updates

    to the database)

    Triggers can generate a log of events to support auditing andsecurity checks

    Triggers can be used to gather statistics on table accesses and

    20