trigger-140121123204-phpapp01

download trigger-140121123204-phpapp01

of 28

Transcript of trigger-140121123204-phpapp01

  • 7/27/2019 trigger-140121123204-phpapp01

    1/28

    Trigger

    V. Saranya AP/CSE,

    Sri Vidya College of Engg & Tech, virudhunagar

  • 7/27/2019 trigger-140121123204-phpapp01

    2/28

    Example: 1

  • 7/27/2019 trigger-140121123204-phpapp01

    3/28

    Example : 2

  • 7/27/2019 trigger-140121123204-phpapp01

    4/28

    Example : 3

  • 7/27/2019 trigger-140121123204-phpapp01

    5/28

    Trigger

    A procedure that starts automatically if

    specified changes occur to the DBMS

  • 7/27/2019 trigger-140121123204-phpapp01

    6/28

    Triggers (Active database)

    Three parts: Event (activates the trigger)

    Condition (tests whether the triggers should run)[Optional]

    Action(what happens if the trigger runs)

    Semantics:

    When event occurs, and condition is satisfied, theaction is performed.

  • 7/27/2019 trigger-140121123204-phpapp01

    7/28

    TriggersEvent,Condition,Action

    Events could be :BEFORE|AFTER INSERT|UPDATE|DELETE ON

    e.g.: BEFORE INSERT ON Professor

    Condition is SQL expression or even an SQLquery (query with non-empty result meansTRUE)

    Action can be many different choices :

    SQL statements , even DDL and transaction-oriented statements likecommit.

  • 7/27/2019 trigger-140121123204-phpapp01

    8/28

    Example Trigger

    Assume our DB has a relation schema :

    Professor (pNum, pName, salary)

    We want to write a trigger that :

    Ensures that any new professorinserted has salary >= 60000

  • 7/27/2019 trigger-140121123204-phpapp01

    9/28

    Example Trigger

    CREATE TRIGGER minSalary BEFOREINSERTONProfessor

    for what context ?

    BEGIN

    check for violation here ?

    END;

    Event

    Condition

  • 7/27/2019 trigger-140121123204-phpapp01

    10/28

    Example Trigger

    CREATE TRIGGER minSalary BEFOREINSERT ON Professor

    FOR EACH ROW

    BEGIN

    Violation of Minimum ProfessorSalary?

    END;

    trigger is performedfor each row inserted

  • 7/27/2019 trigger-140121123204-phpapp01

    11/28

    Example TriggerCREATE TRIGGER minSalary BEFORE INSERT ON

    Professor

    FOR EACH ROW

    BEGIN

    IF (:new.salary < 60000)

    THEN RAISE_APPLICATION_ERROR (-20004,

    Violation of MinimumProfessor Salary);

    END IF;

    END;

  • 7/27/2019 trigger-140121123204-phpapp01

    12/28

    Example trigger

    CREATE TRIGGER minSalary BEFORE INSERT ON ProfessorFOR EACH ROW

    DECLARE temp int; -- dummy variable notneeded

    BEGIN

    IF (:new.salary < 60000)

    THEN RAISE_APPLICATION_ERROR (-20004,Violation of Minimum Professor

    Salary);END IF;

    temp := 10; -- to illustrate declaredvariables

    END;

  • 7/27/2019 trigger-140121123204-phpapp01

    13/28

    Details of Trigger Example

    BEFORE INSERT ON Professor

    This trigger is checked before the tuple is inserted

    FOR EACH ROW

    specifies that trigger is performed for each rowinserted

    :new

    refers to the new tuple inserted

    If (:new.salary < 60000) then an application error is raised and hence the

    row is not inserted; otherwise the row is inserted.

    Use error code: -20004;

    this is in the valid range

  • 7/27/2019 trigger-140121123204-phpapp01

    14/28

    Example Trigger Using

    ConditionCREATE TRIGGER minSalary BEFORE INSERT ON Professor

    FOR EACH ROW

    WHEN (new.salary < 60000)

    BEGINRAISE_APPLICATION_ERROR (-20004,

    Violationof Minimum Professor Salary);

    END;

    Conditions can refer to old/new values of tuplesmodified by the statement activating the trigger.

    Condition

  • 7/27/2019 trigger-140121123204-phpapp01

    15/28

    Triggers: REFERENCING

    CREATE TRIGGER minSalary BEFORE INSERT ON Professor

    REFERENCING NEW as newTuple

    FOR EACH ROW

    WHEN (newTuple.salary < 60000)

    BEGIN

    RAISE_APPLICATION_ERROR (-20004,

    Violation of Minimum Professor Salary);

    END;

  • 7/27/2019 trigger-140121123204-phpapp01

    16/28

    Example Trigger

    CREATE TRIGGER minSalary

    BEFORE UPDATEON Professor

    REFERENCING OLD AS oldTuple NEW as newTuple

    FOR EACH ROW

    WHEN (newTuple.salary < oldTuple.salary)

    BEGIN

    RAISE_APPLICATION_ERROR (-20004, Salary

    Decreasing !!);END;

    Ensure that salary does not decrease

  • 7/27/2019 trigger-140121123204-phpapp01

    17/28

    Another Trigger Example (SQL:99)

    CREATE TRIGGER youngSailorUpdate

    AFTER INSERT ON SAILORS

    REFERENCING NEW TABLEASNewSailorsFOR EACH STATEMENT

    INSERT

    INTO YoungSailors(sid, name, age, rating)

    SELECT sid, name, age, ratingFROM NewSailors N

    WHERE N.age

  • 7/27/2019 trigger-140121123204-phpapp01

    18/28

    Types of Triggers

    This section describes the different types of triggers:

    Row level triggers

    Trigger once foreach row in a transaction.

    Statement level triggers

    Triggers execute once foreach transaction.

    Before and after triggers Triggers can be executed immediately before and

    after INSERT, UPDATE and DELETE.

    Defined by triggeringtransaction & level at which thetrigger is executed

  • 7/27/2019 trigger-140121123204-phpapp01

    19/28

    Row vs Statement Level Trigger

    Example: Consider a relation schema

    Account (num, amount)

    where we will allow creation of new accounts

    only during normal business hours.

  • 7/27/2019 trigger-140121123204-phpapp01

    20/28

    Example: Statement level trigger

    CREATE TRIGGER MYTRIG1

    BEFORE INSERTON AccountFOR EACH STATEMENT --- is default

    BEGIN

    IF (TO_CHAR(SYSDATE,dy) IN (sat,sun))

    OR

    (TO_CHAR(SYSDATE,hh24:mi) NOT BETWEEN 08:00

    AND 17:00)

    THEN

    RAISE_APPLICATION_ERROR(-20500,Cannotcreate new account now !!);

    END IF;

    END;

  • 7/27/2019 trigger-140121123204-phpapp01

    21/28

    When to use BEFORE/AFTER

    Based on efficiency considerations orsemantics.

    Suppose we perform statement-level afterinsert, then all the rows are inserted first,then if the condition fails,and all the inserted rows must berolledback

    Not very efficient !!

  • 7/27/2019 trigger-140121123204-phpapp01

    22/28

    Combining multiple events into one

    triggerCREATE TRIGGER salaryRestrictions

    AFTER INSERT OR UPDATEON Professor

    FOR EACH ROW

    BEGINIF (INSERTING AND :new.salary < 60000) THEN

    RAISE_APPLICATION_ERROR (-20004, 'below minsalary'); END IF;

    IF (UPDATING AND :new.salary < :old.salary)

    THEN RAISE_APPLICATION_ERROR (-20004,Salary Decreasing !!'); END IF;

    END;

    1

    2

  • 7/27/2019 trigger-140121123204-phpapp01

    23/28

    Summary : Trigger Syntax

    CREATE TRIGGER

    BEFORE|AFTER INSERT|DELETE|UPDATE

    [OF ] ON |

    [REFERENCING [OLD AS ] [NEW AS]]

    [FOR EACH ROW] (default is FOR EACH STATEMENT)

    [WHEN ()]

    ;

  • 7/27/2019 trigger-140121123204-phpapp01

    24/28

    Some Points about Triggers

    Check the system tables :

    user_triggers

    user_trigger_cols user_errors

    ORA-04091: mutating relation problem

    In a row level trigger, you cannothave thebody refer to the table specified in the event

    Also INSTEAD OFtriggers can be specified on

    views

  • 7/27/2019 trigger-140121123204-phpapp01

    25/28

    To Show Compilation Errors

    SELECT line, position, text

    FROM user_errors

    WHERE name = 'MY_TRIGGER'AND TYPE = 'TRIGGER

    In SQL*Plus, you can also use the following

    shortcut:

    SQL> SHOW ERRORS TRIGGER MY_TRIGGER

  • 7/27/2019 trigger-140121123204-phpapp01

    26/28

    Mutating Trigger

    Trigger that triggers itself

  • 7/27/2019 trigger-140121123204-phpapp01

    27/28

    Constraints versus Triggers

    Constraints are useful for database consistency More opportunity for optimization

    Not restricted into insert/delete/update

    Triggers are flexible and powerful Alerts

    Event logging for auditing

    Security enforcement

    Analysis of table accesses (statistics)

    Workflow and business intelligence

    But can be hard to understand Several triggers (Arbitrary order unpredictable !?)

    Chain triggers (When to stop ?)

    Recursive triggers (Termination?)

  • 7/27/2019 trigger-140121123204-phpapp01

    28/28

    Purpose of Triggers

    To generate data automatically

    To enforce complex integrity constraints

    To customize complex security authorization

    To maintain replicate tables

    To audit data modifications.