By Muhammad Fahim Khan

download By Muhammad Fahim Khan

of 42

Transcript of By Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    1/42

    By Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    2/42

    Objectives

    Trigger ConceptTrigger RequirementTrigger - UsesTrigger Types

    Referencing columns :OLD Vs :NewTrigger Important points

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    3/42

    Triggers Concept

    Triggers are special PL/SQL construct similar to procedures.

    However, a procedure is executed explicitly from another block via a procedure call.

    A trigger is executed implicitly or Automatically

    whenever the triggering event happens.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    4/42

    Triggers Concept

    Triggers are basically created and stored likestored procedure in database.

    Once they are stored then they are automaticallycompiled and called by database itself, under a

    given condition or what we call as TriggeringEvent.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    5/42

    Triggers Why

    Triggers provides support for followingactivities in database:

    Validation : There are certain validations on tableand its data that we cannot provide using constraintsso for all such cases we use triggers for validations.

    Eg:In a bank if we want to provide some validation for withdrawal of a money in transaction table bychecking the balance in the Account master table.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    6/42

    Triggers Why

    Auditing : Triggers are automatically called whensome action happens on a table, so they can be usedto keep track for all the activities happening on a

    table.

    Eg:Triggers can be written on a table emp, dept etc tocheck and store the name of the person , date andtime of any operation and type of operationhappening on these tables in some other audit table .

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    7/42

    Triggers Why

    Backup : Triggers can be used to automatically back up some crucial data.

    Eg:Trigger can be written on Emp table to store theempno , name and salary for future use in some back table, if somebody deletes the record in the emp.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    8/42

    Triggers Why

    Restrictions: Triggers can be used to imposerestriction or prohibit some operation under certainconditions.

    Eg:Trigger can be written on Emp table to disallow or

    prohibit anybody from deleting or modifying any

    record in Emp table on Sat and Sun.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    9/42

    Triggers Types

    DML Triggers : Triggers on INSERT ,UPDATE , DELETE .

    DML triggers are used by developers for validations , auditing , backup etc.

    DML triggers are written on tables

    Requires no special privileges.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    10/42

    Triggers Types

    System level triggers : Database level Trigger : Triggers on startup and shutdown of

    database.

    Schema level Trigger :

    Triggers on Logon and Logoff from schema. DDL Trigger : Triggers on CREATE , ALTER , DROP

    System level trigger are used by Database Administrator (DBA)for monitoring and administration purposes

    Requires special privileges

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    11/42

    Triggers

    Note :

    In current session we will deal with DMLtriggers only as they are used for tablelevel operations. Other trigger requires

    4. Special privileges (DBA)5. Not in the scope/expectation of the current

    session

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    12/42

    Triggers Syntax

    CREATE [OR REPLACE] TRIGGER

    {TRIGGERING_TIME }

    {TRIGGERING_EVENT } ON < TABLE_NAME >

    [FOR EACH ROW [WHEN (< TRIGGER_CONDITION >)] ]

    DECLARE

    BEGIN

    EXCEPTION

    END;

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    13/42

    Triggers Syntax

    TRIGGERING_TIME Before : Specify before if database should

    fire trigger (execute trigger) before triggeringevent.

    After :Specify After if database should firetrigger (execute trigger) after triggering event.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    14/42

    Triggers Syntax

    TRIGGERING_EVENT INSERT : If trigger should be fired or executed for Insert

    operation.

    UPDATE : If trigger should be fired or executed for updateoperation.

    DELETE : If trigger should be fired or executed for Deleteoperation.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    15/42

    Triggers Syntax

    TABLE_NAME Name of the table for which trigger should execute.

    Remember one DML trigger is always associated withone table i.e. a same DML trigger cannot be written for two different tables.

    Each trigger has a unique name.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    16/42

    Triggers Syntax

    NOTE:For practice of trigger examples.

    Please make your own copy of table and

    give different name for triggers preferablywith your own employee no else you willover ride others persons triggers or two same

    type of triggers on same table will causeambiguity and errors.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    17/42

    Triggers Syntax

    FOR EACH ROW [WHEN (< TRIGGER_CONDITION >)]

    DML triggers can be Row level : Executes one time for each row.

    Statement level : Executes one time for each statement.

    For each row is optional , if you specify it then trigger is rowlevel trigger. When and condition should not be given here.

    If we do not specify for each row then it is statement level ,you can give some condition with WHEN for the statementlevel trigger , it can be some query etc but not a sub-query

    Muhammad Fahim Khan

    h d h h

  • 8/14/2019 By Muhammad Fahim Khan

    18/42

    Triggers SyntaxROW Level Vs Statement Level Example : Suppose there is a Before Update trigger on emp table.

    So if we give a update query on SQL prompt then trigger will beexecuted automatically by oracle.

    Update Emp Set Sal = Sal + 500 ;

    Query is nothing but its like a statement and this update query canupdate many rows in a table Emp here.

    If we want trigger to execute only once before update for all thoserows then we will use statement level i.e. without for each row .

    If we want trigger to execute once before every row the abovestatement or query will update then row level trigger i.e. with for each row .

    Muhammad Fahim Khan

    M h d F hi Kh

  • 8/14/2019 By Muhammad Fahim Khan

    19/42

    Triggers Syntax

    Mostly Row level is used for DML Triggers.

    For Validation , Backup , Auditing , Restriction etcrow level can be used.

    Statement level mostly is used for Auditing purposes

    only.

    Muhammad Fahim Khan

    M h d F hi Kh

  • 8/14/2019 By Muhammad Fahim Khan

    20/42

    Triggers Syntax

    DECLARE : Declaring local variables for the trigger.

    BEGIN : Contains the actual code for the trigger toexecute whenever triggering event happens.

    EXCEPTION: Exception or Error handling code.

    Basically these are same as normal block of PL SQL

    Muhammad Fahim Khan

    M h d F hi Kh

  • 8/14/2019 By Muhammad Fahim Khan

    21/42

    Trigger Important

    Transaction control statements like Commit , Rollback etc are not allowed in trigger.

    Create , Alter and Drop (DDL) statements are notallowed in trigger.

    Insert , Update and Delete (DML) inside the trigger code is allowed but only on tables other then the tableon which trigger itself is written.

    Muhammad Fahim Khan

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    22/42

    Trigger Important

    Select query inside the trigger code on all tables isallowed but query on the table on which trigger iswritten can cause some problems , precautions should

    be taken.

    Calling procedure , functions and packages insidetrigger is allowed but those procedures , functions and

    packages should not contain any commit or rollback statements.

    Muhammad Fahim Khan

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    23/42

    Trigger Important

    Mutating Table : "Mutating" means "changing".A mutating table is a table that is currently beingmodified by an update, delete, or insert statement. Whena trigger tries to refer a table that is in state of flux (beingchanged), it is considered "mutating" and raises an error

    Another way this error can occur is if the trigger hasstatements to change the primary, foreign or unique key

    columns of the table off which it fires. If we write somecode in trigger that can cause ambiguity with that table :

    Example If we write a Insert query on the table in aInsert trigger of that table itself which is not allowed then

    at runtime it will give Mutation error .

    Muhammad Fahim Khan

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    24/42

    Trigger Important

    To avoid mutation problem avoid using Insert ,update , Delete or Select query on a mutating

    table in the trigger code i.e. the same table onwhich the trigger is written.

    However you can write Insert , Update andDelete query on other tables in the trigger code.

    Muhammad Fahim Khan

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    25/42

    :OLD and :NEW

    Inside the trigger code since we cannot refer to thetable on which trigger is written directly so if we wantto check or change or verify the value in some columnof that table we can used :OLD and : NEW.

    :OLD and :NEW is only used in row level triggers.

    Muhammad Fahim Khan

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    26/42

    :OLD and :NEW

    :OLD and :NEW refers to the row of the table onwhich trigger is currently executing.

    Any column of that row can be referred to as:OLD.Column_Name or :NEW.Column_Name

    Example: OLD.Empno , :OLD.Ename ,

    :NEW.Empno etc

    Muhammad Fahim Khan

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    27/42

    :OLD and :NEW

    :OLD Vs :NEW

    In case of INSERT new data comes to table so we can refer to thecolumns of that new row of the table in the trigger with :NEW.

    :OLD is invalid in Insert triggers.

    In case of DELETE old data is deleted from table so we can refer to the columns of that old row of the table being deleted in thetrigger with :OLD.

    :NEW is invalid in Delete triggers.

    Muhammad Fahim Khan

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    28/42

    :OLD and :NEW

    :OLD Vs :NEW

    In case of UPDATE old data is modified with newdata so we can refer to the columns of that row of thetable in the trigger with both :OLD and :NEW.

    :OLD will point to old data of the row.

    :New will point to new data being updated for thatrow.

    Muhammad Fahim Khan

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    29/42

    or Invalid:OLD.Col_Name

    DELETE

    :NEW.Col_Name:OLD.Col_NameUDATE

    :NEW.Col_Name or InvalidINSERT

    :NEW:OLD

    Muhammad Fahim Khan

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    30/42

    :OLD and :NEW

    Example : In dept table there is one record

    Deptno Dname Loc10 Admin Pune

    Suppose there is a update trigger on this table then wecan have both :OLD and : NEW in that trigger.

    Suppose we give the update query as :Update Dept Set Loc = Mumbai where Deptno = 10;

    Cont.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    31/42

    :OLD and :NEW

    Inside the trigger then

    :OLD.Deptno 10

    :OLD.Dname Admin

    :OLD.Loc Pune

    :NEW.Deptno 10:NEW.Dname Admin

    :NEW.Loc Mumbai

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    32/42

    Trigger Important

    One table we can have all types of trigger each with unique name i.e.Emp can have 12 triggers Before Update Statement level

    Before Update Row level After Update Row level

    After Update Statement level

    Before Insert Statement level Before Insert Row level

    After Insert Row level

    After Insert Statement level

    Before Delete Statement level

    Before Delete Row level

    After Delete Row level

    After Delete Statement level

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    33/42

    Trigger Important

    Suppose if we have four trigger on emp table

    Before Update Statement level

    Before Update Row level After Update Row level

    After Update Statement level

    Cont.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    34/42

    Trigger Important

    Update Emp set Sal = Sal + 500 where Deptno = 10;Suppose this query affects 3 rows.

    Trigger will be executed as follows and in followingorder.

    Before Update Statement level (Only Once) Before Update Row level After Update Row level

    Before Update Row level After Update Row level Before Update Row level After Update Row level After Update Statement level (Only Once)

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    35/42

    Trigger Important

    Row level is executed one time each for each row.

    Statement level only once for one query.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    36/42

    Trigger Important

    However on same table you cannot haveexactly two same type of triggers , they cancause problems i.e. Two triggers on emp both

    before update row level ,can cause errors.

    As table will not understand which one toexecute for each row before update happens.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    37/42

    Trigger Important

    Triggers are one of the important andvery excellent feature of Oracle PL SQL

    but should be used properly as it slowsdown the speed of DML operations.

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    38/42

    ExampleCreate following tables for examples Tables.SQL

    Example 51 Sample51.SQL

    Example 52 Sample52.SQL

    Example 53 Sample53.SQL

    Example 54 Sample54.SQL

    Example 55 Sample55.SQL

    Example 56 Sample56.SQL

    Muhammad Fahim Khan

    http://tables.sql/http://sample51.sql/http://sample52.sql/http://sample53.sql/http://sample54.sql/http://sample55.sql/http://sample56.sql/http://sample56.sql/http://sample55.sql/http://sample54.sql/http://sample53.sql/http://sample52.sql/http://sample51.sql/http://tables.sql/
  • 8/14/2019 By Muhammad Fahim Khan

    39/42

    USER_TRIGGERS

    To see all the triggers created you can view USER_TRIGGERS

    To see the structure Desc USER_Triggers

    To see triggers for EMP_ESG table

    select trigger_type, triggering_event,table_name, from user_triggers wheretable_name = EMP_ESG';

  • 8/14/2019 By Muhammad Fahim Khan

    40/42

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    41/42

    Deleting TRIGGERS

    To delete trigger

    Drop trigger ;

    Example:

    Drop Trigger Emp_Up_1;

    Muhammad Fahim Khan

  • 8/14/2019 By Muhammad Fahim Khan

    42/42

    Next Session:

    Object types inOracle

    Thank you !!Thank you !!