plsql lecture 7

Upload: cavad565

Post on 02-Jun-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 Plsql Lecture 7

    1/20

    RDBMS Using OracleRDBMS Using Oracle

    Creating Database TriggersCreating Database Triggers

    [email protected]

    Triggers OverviewTriggers Overview

    A trigger is a PL/SQL block that executes A trigger is a PL/SQL block that executeswhenever a particular event takes place.whenever a particular event takes place.

    In this lecture we will learnIn this lecture we will learn

    Database triggers and their useDatabase triggers and their useHow to create database triggersHow to create database triggersTriggers firing rulesTriggers firing rules

  • 8/10/2019 Plsql Lecture 7

    2/20

  • 8/10/2019 Plsql Lecture 7

    3/20

    Trigger Components contd..Trigger Components contd..

    Trigger Body:Trigger Body:What action should the trigger perform?What action should the trigger perform?

    [DECLARE][DECLARE]BEGINBEGIN[EXCEPTION][EXCEPTION]END;END;

    Trigger Components contd..Trigger Components contd..

    Trigger TypeTrigger Type

    How many times should the trigger body executeHow many times should the trigger body executewhen the triggering event takes place?when the triggering event takes place?

    11-- Statement [Default]Statement [Default]

    The trigger body executes once for the triggeringThe trigger body executes once for the triggeringevent.event.

    22 -- RowRow

    The trigger body executes once for each rowThe trigger body executes once for each rowaffected by the triggering event.affected by the triggering event.

  • 8/10/2019 Plsql Lecture 7

    4/20

    Lets see the difference BetweenLets see the difference Between

    Statement & Row level trigger Statement & Row level trigger

    With a general exampleWith a general example

    Statement & Row level trigger Statement & Row level trigger

    SQL> Insert into deptSQL> Insert into deptvalues(50, EDUCATION, NEW YORK);values(50, EDUCATION, NEW YORK);

    SQL> UpdateSQL> Update empemp setset salsal == salsal * 1.1;* 1.1;

    2- RowThe trigger body executes once for eachThe trigger body executes once for eachrow affected by the triggering event.row affected by the triggering event.

    Statement [Default]The trigger body executes once forThe trigger body executes once for

    the triggering event.the triggering event.

  • 8/10/2019 Plsql Lecture 7

    5/20

    Creating Trigger Creating Trigger

    Syntax for creating Statement Trigger Syntax for creating Statement Trigger

    CRAETE [OR REPLACE] TRIGGERCRAETE [OR REPLACE] TRIGGER triger_nametriger_name

    timingtiming (Before or After)(Before or After) eventevent (INSERT, DELETE, UPDATE)(INSERT, DELETE, UPDATE)

    on >

    PL/SQL Block;PL/SQL Block;

  • 8/10/2019 Plsql Lecture 7

    6/20

    Creating Statement Trigger Creating Statement Trigger

    CREATE OR REPLACE TRIGGER SECURE_EMPCREATE OR REPLACE TRIGGER SECURE_EMPBEFORE INSERT ON EMPBEFORE INSERT ON EMPBEGINBEGIN

    IFIF(TO_CHAR (SYSDATE, 'DY') IN ('SAT','SUN','TUE'))(TO_CHAR (SYSDATE, 'DY') IN ('SAT','SUN','TUE'))

    THENTHENRAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR( --20500,20500, 'YOU CAN ONLY'YOU CAN ONLYINSERT DATA INTO EMP DURING WEDNESDAY TOINSERT DATA INTO EMP DURING WEDNESDAY TO

    FRIDAYFRIDAY ');');END IF;END IF;

    END;END;

    Output: trigger createdOutput: trigger created

    SQL> INSERT INTO EMP(EMPNO, DEPTNO)SQL> INSERT INTO EMP(EMPNO, DEPTNO)VALUES(1234, 30);VALUES(1234, 30);

    * ERROR* ERRORORAORA --20500: YOU CAN ONLY INSERT DATA INTO EMP20500: YOU CAN ONLY INSERT DATA INTO EMPDURING WEDNESDAY TO FRIDAYDURING WEDNESDAY TO FRIDAY

  • 8/10/2019 Plsql Lecture 7

    7/20

    Example # 2Example # 2

    CREATE OR REPLACE TRIGGER SECURE_EMPCREATE OR REPLACE TRIGGER SECURE_EMPBEFORE INSERT OR UPDATE OR DELETE ON EMPBEFORE INSERT OR UPDATE OR DELETE ON EMPBEGINBEGIN

    IFIF (TO_CHAR (SYSDATE, 'DY') IN ('SAT','SUN')) OR(TO_CHAR (SYSDATE, 'DY') IN ('SAT','SUN')) OR(TO_CHAR (SYSDATE, 'HH24') NOT BETWEEN '08' AND 18)(TO_CHAR (SYSDATE, 'HH24') NOT BETWEEN '08' AND 18)

    THENTHENIF DELETING THENIF DELETING THEN

    RAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR( --20501, 'YOU CAN ONLY20501, 'YOU CAN ONLYDELETE DURING NORMAL OFFICE HOURS');DELETE DURING NORMAL OFFICE HOURS');

    ELSIF INSERTING THENELSIF INSERTING THENRAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR( --20507, 'YOU CAN ONLY20507, 'YOU CAN ONLYINSERTINSERT DATA INTO EMP DURING OFFICE HOURS');DATA INTO EMP DURING OFFICE HOURS');

    ELSIF UPDATING ('SAL') THENELSIF UPDATING ('SAL') THENRAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR( --20502, 'YOU CAN ONLY20502, 'YOU CAN ONLYUPADTEUPADTE SALERYSALERY DURING OFFICE HOURS');DURING OFFICE HOURS');

    ELSEELSERAISE_APPLICATION_ERROR(RAISE_APPLICATION_ERROR( --20504, 'YOU CAN ONLY20504, 'YOU CAN ONLYUPADTEUPADTE DURING OFFICE HOURS');DURING OFFICE HOURS');

    END IF;END IF;END IF;END IF;

    END;END;

  • 8/10/2019 Plsql Lecture 7

    8/20

    SQL> INSERT INTO EMP(EMPNO, DEPTNO) VALUES(12345, 40);SQL> INSERT INTO EMP(EMPNO, DEPTNO) VALUES(12345, 40);INSERT INTO EMP(EMPNO, DEPTNO) VALUES(12345, 40)INSERT INTO EMP(EMPNO, DEPTNO) VALUES(12345, 40)

    **

    ERROR at line 1:ERROR at line 1:ORAORA --20507: YOU CAN ONLY INSERT DATA INTO EMP DURING20507: YOU CAN ONLY INSERT DATA INTO EMP DURING

    OFFICE HOURSOFFICE HOURS

    SQL> UPDATE EMPSQL> UPDATE EMP2 SET SAL =2 SET SAL = SALSAL * 10;* 10;

    UPDATE EMPUPDATE EMP**

    ERROR at line 1:ERROR at line 1:ORAORA --20502: YOU CAN ONLY UPADTE SALERY DURING OFFICE20502: YOU CAN ONLY UPADTE SALERY DURING OFFICE

    HOURSHOURS

    SQL>SQL>1 UPDATE EMP1 UPDATE EMP2* SET EMPNO = 12452* SET EMPNO = 1245

    UPDATE EMPUPDATE EMP**

    ERROR at line 1:ERROR at line 1:ORAORA --20504: YOU CAN ONLY UPADTE DURING OFFICE HOURS20504: YOU CAN ONLY UPADTE DURING OFFICE HOURS

  • 8/10/2019 Plsql Lecture 7

    9/20

    TriggersTriggers contdcontd Creating a Row TriggersCreating a Row Triggers

    [email protected]

    Review:Review: Trigger Components contd..Trigger Components contd..Trigger TypeTrigger TypeHow many times should theHow many times should thetrigger body execute whentrigger body execute whenthe triggering event takesthe triggering event takesplace?place?

    11 -- Statement [Default]Statement [Default]

    The trigger body executes onceThe trigger body executes oncefor the triggering event.for the triggering event.

    22 -- RowRow

    The trigger body executesThe trigger body executesonce for each row affected byonce for each row affected bythe triggering event.the triggering event.

    SQL> Insert into deptSQL> Insert into dept

    values(50, EDUCATION, NEWvalues(50, EDUCATION, NEWYORK);YORK);

    SQL> UpdateSQL> Update empemp setset salsal == salsal * 1.1;* 1.1;

    2- RowThe trigger body executes once for eachThe trigger body executes once for eachrow affected by the triggering event.row affected by the triggering event.

    Statement [Default]The trigger body executes once forThe trigger body executes once forthe triggering event.the triggering event.

  • 8/10/2019 Plsql Lecture 7

    10/20

    Creating Row Trigger Creating Row Trigger

    Syntax for creating ROW Trigger Syntax for creating ROW Trigger

    CRAETECRAETE [OR REPLACE][OR REPLACE] TRIGGERTRIGGER triger_nametriger_nametimingtiming (Before or After)(Before or After) eventevent (INSERT, DELETE, UPDATE)(INSERT, DELETE, UPDATE)

    on on

    FOR EACH ROWFOR EACH ROW[WHEN condition][WHEN condition]

    PL/SQL Block;PL/SQL Block;

    This condition ischecked for each row

  • 8/10/2019 Plsql Lecture 7

    11/20

    ProblemProblem

    Create a row trigger to keep aCreate a row trigger to keep arunning count of DMLrunning count of DML

    operations by different usersoperations by different userson a database table [EMP].on a database table [EMP].

    113300EMPEMPXYZXYZ991100EMPEMP ALI ALI445544EMPEMPSCOTTSCOTT

    C_UpdateC_InsertC_DeleteTable nameUsername

    Problem SolutionProblem SolutionHere we will create a [AFTER TIMING] trigger as we want to

    Keep track of all successful DML operations

    AndWe will use trigger FOR EACH ROW as we want tocount number of rows affected

    by the DML statement (in case of Delete or update).

  • 8/10/2019 Plsql Lecture 7

    12/20

    CREATE OR REPLACE TRIGGER DML_COUNT_EMPCREATE OR REPLACE TRIGGER DML_COUNT_EMP AFTER INSERT OR UPDATE OR DELETE ON EMP AFTER INSERT OR UPDATE OR DELETE ON EMPFOR EACH ROWFOR EACH ROWBEGINBEGIN

    IF DELETING THENIF DELETING THENUPDATE DML_EMP set C_DELETE = C_DELETE + 1UPDATE DML_EMP set C_DELETE = C_DELETE + 1Where USERNAME = user andWhere USERNAME = user and tablenametablename = EMP;= EMP;

    ELSIF INSERTING THENELSIF INSERTING THENUPDATE DML_EMP set C_INSERT = C_INSERT + 1UPDATE DML_EMP set C_INSERT = C_INSERT + 1Where USERNAME = user andWhere USERNAME = user and tablenametablename = EMP;= EMP;

    ELSIF UPDATING ('SAL') THENELSIF UPDATING ('SAL') THENUPDATE DML_EMP set C_UPDATE = C_UPDATE + 1UPDATE DML_EMP set C_UPDATE = C_UPDATE + 1Where USERNAME = user andWhere USERNAME = user and tablenametablename = EMP;= EMP;

    ELSEELSEUPDATE DML_EMP set C_UPDATE = C_UPDATE + 1UPDATE DML_EMP set C_UPDATE = C_UPDATE + 1Where USERNAME = user andWhere USERNAME = user and tablenametablename = EMP;= EMP;

    END IF;END IF;END;END;

    SQL> insert intoSQL> insert into emp(empnoemp(empno ,, deptnodeptno ) values(1, 10)) values(1, 10)1 row created.1 row created.

    SQL> select * fromSQL> select * from dml_empdml_emp ;;

    USERNAMEUSERNAME TABLENAME C_DELETE C_UPDATETABLENAME C_DELETE C_UPDATEC_INSERTC_INSERT

    ---------------------------------------- ---------------------------------------- ------------------ ---------------- -- ------------------SCOTT EMP 0SCOTT EMP 0 00 11KAMRAN EMP 0KAMRAN EMP 0 00 00

  • 8/10/2019 Plsql Lecture 7

    13/20

    SQL> updateSQL> update empemp setset deptnodeptno = 10;= 10;

    15 rows updated.15 rows updated.

    SQL> select * fromSQL> select * from dml_empdml_emp ;;

    USERNAME TABLENAME C_DELETE C_UPDATEUSERNAME TABLENAME C_DELETE C_UPDATEC_INSERTC_INSERT

    ------------------------------ ---------------------------------------- ------------------ ------------------ ------------------SCOTT EMP 0SCOTT EMP 0 1515 11KAMRAN EMP 0KAMRAN EMP 0 0 00 0

    Difference betweenDifference betweenTriggers and ProceduresTriggers and Procedures

  • 8/10/2019 Plsql Lecture 7

    14/20

    Use CREATE PROCEDUREUse CREATE PROCEDURE

    Data Dictionary containsData Dictionary containssource and psource and p --codecode

    COMMIT and ROLLBACK areCOMMIT and ROLLBACK areallowed.allowed.

    Invoked ExplicitlyInvoked Explicitly

    Use CREATE TRIGGERUse CREATE TRIGGER

    Data Dictionary containsData Dictionary containssource and psource and p --codecode

    COMMIT and ROLLBACK areCOMMIT and ROLLBACK arenot allowed.not allowed.

    Invoked ImplicitlyInvoked Implicitly

    ProceduresTriggers

    Difference between Triggers and ProceduresDifference between Triggers and Procedures

    OLD & NEWOLD & NEWIn triggers we can also track usersIn triggers we can also track users

    activities performed against any table.activities performed against any table.We can record the values both beforeWe can record the values both beforeand after the data changes by usingand after the data changes by using

    OLD and NEW qualifiers withOLD and NEW qualifiers withrespective column names.respective column names.

  • 8/10/2019 Plsql Lecture 7

    15/20

    Syntax for creating ROW Trigger Syntax for creating ROW Trigger

    CRAETE [OR REPLACE] TRIGGERCRAETE [OR REPLACE] TRIGGER triger_nametriger_nametimingtiming (Before or After)(Before or After) eventevent (INSERT, DELETE, UPDATE)(INSERT, DELETE, UPDATE)on >[REFERENCING OLD AS old | NEW as new][REFERENCING OLD AS old | NEW as new]FOR EACH ROWFOR EACH ROW

    [WHEN condition][WHEN condition]

    PL/SQL Block;PL/SQL Block;This condition is

    checked for each row

    SQL> create tableSQL> create table audit_emp_valuesaudit_emp_values(user_name varchar(20),(user_name varchar(20),timestamp date,timestamp date,id number(10),id number(10),old_enameold_ename varchar2(20),varchar2(20),new_enamenew_ename varchar2(20),varchar2(20),old_salold_sal number(10),number(10),new_salnew_sal number(10));number(10));

    Table created.Table created.SQL> desc AUDIT_EMP_VALUES;Name Null? Type------------------------------- -------- ----USER_NAME VARCHAR2(20)TIMESTAMP DATEID NUMBER(10)OLD_ENAME VARCHAR2(20)NEW_ENAME VARCHAR2(20)OLD_SAL NUMBER(10)NEW_SAL NUMBER(10)

    . ..

  • 8/10/2019 Plsql Lecture 7

    16/20

    Now a trigger that will track users activities Now a trigger that will track users activities performed against EMP table. performed against EMP table.

    We will record the values both before and after theWe will record the values both before and after thedata changes.data changes.

    Using OLD and NEW

    CREATE OR REPLACE TRIGGERCREATE OR REPLACE TRIGGER audit_emp_valuesaudit_emp_valuesAfter DELETE OR INSERT OR UPDATE onAfter DELETE OR INSERT OR UPDATE on empemp

    FOR EACH ROW

    BEGINBEGINInsert intoInsert into audit_emp_valuesaudit_emp_values (user_name, timestamp, id,(user_name, timestamp, id,

    old_ename,new_enameold_ename,new_ename ,, old_salold_sal ,, new_salnew_sal ))

    Values (Values ( user,sysdateuser,sysdate , :, :old.empnoold.empno , :, :old.enameold.ename ,,::new.enamenew.ename , :, :old.sal,:new.salold.sal,:new.sal ););

    END;END;

  • 8/10/2019 Plsql Lecture 7

    17/20

    INSERTINSERT

    SQL> insert intoSQL> insert into emp(empnoemp(empno , ename,, ename, salsal ))values(1111, 'TEST', 5000);values(1111, 'TEST', 5000);

    SQL> select USER_NAME, TIMESTAMP , NEW_ENAME, NEW_SALSQL> select USER_NAME, TIMESTAMP , NEW_ENAME, NEW_SALfromfrom Audit_emp_values Audit_emp_values ;;

    USER_NAME TIMESTAMP NEW_ENAME NEW_SALUSER_NAME TIMESTAMP NEW_ENAME NEW_SAL-------------------------------- ------------------------ ---------------------------------------- ------------------SCOTT 10SCOTT 10 --DECDEC --04 TEST 500004 TEST 5000

    SQL> updateSQL> update empemp2 set2 set salsal = 6000= 60003 where3 where empnoempno = 1111;= 1111;

    1 row updated.1 row updated.

    SQL> select * fromSQL> select * from audit_emp_valuesaudit_emp_values ;;

    USER_NAME TIMESTAMP ID OLD_ENAMEUSER_NAME TIMESTAMP ID OLD_ENAME NEW_ENAMENEW_ENAME OLD_SALOLD_SAL NEW_SALNEW_SAL---------------------------------------- ------------------ ------------------ ---------------------------------------- ---------------------------------------- ------------------ ------------------SCOTT 10SCOTT 10 --DECDEC --04 TEST 500004 TEST 5000SCOTT 10SCOTT 10 --DECDEC --04 1111 TEST TEST 5000 600004 1111 TEST TEST 5000 6000

    UPDATEUPDATE

  • 8/10/2019 Plsql Lecture 7

    18/20

    SQL> delete fromSQL> delete from empemp where ename = 'TEST';where ename = 'TEST';

    1 row deleted.1 row deleted.

    USER_NAME TIMESTAMP ID OLD_ENAME NEW_ENAME OLD_SAL NEW_SAL---------------- --------- --------- -------------------- -------------------- --------- ---------SCOTT 10-DEC-04 TEST 5000

    SCOTT 10-DEC-04 1111 TEST TEST 5000 6000SCOTT 10-DEC-04 1111 TEST 6000

    DELETEDELETE

    Think what else we can doThink what else we can dowith triggerswith triggers

    Give suggestions.Give suggestions.

  • 8/10/2019 Plsql Lecture 7

    19/20

    Managing TriggersManaging Triggers

    To Enable or Disable a Trigger To Enable or Disable a Trigger Alter Trigger DISABLE | ENABLE; Alter Trigger DISABLE | ENABLE;

    To Enable or Disable all Trigger on a TableTo Enable or Disable all Trigger on a Table Alter TABLE Alter TABLE DISABLE | ENABLE AllDISABLE | ENABLE All

    TRIGGERS;TRIGGERS;

    Recompile a trigger for a tableRecompile a trigger for a table Alter trigger COMPILE; Alter trigger COMPILE;

    Removing Trigger Removing Trigger DROP TRIGGER ;

  • 8/10/2019 Plsql Lecture 7

    20/20

    ThanksThanks

    Q& A