Top Banner

of 34

DAY 4 Triggers

Jun 03, 2018

Download

Documents

Raja Rajesh
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/11/2019 DAY 4 Triggers

    1/34

    9/13/2007 9:13:55 AMPLSQL Training CSC India Pvt Ltd1

    PL/SQL Training(Database Triggers)

    Srinivas Nagula

    [email protected]

    18-JUL-2011

    To

    22-JUL-2011

  • 8/11/2019 DAY 4 Triggers

    2/34

    PL/SQL Training9/4/20149/4/2014 5:41:44 AM 2

    Database Triggers

    What is a Trigger

    Triggers are named PLSQL blocks with declarative, executable and exception-

    handling sections, similar to procedures and functions

    Triggers are stored as stand alone objects in database, cannot be local to a

    block or package

    Triggers are executed implicitly whenever the triggering event occurs, and

    does not accepts arguments

  • 8/11/2019 DAY 4 Triggers

    3/34

    PL/SQL Training9/4/20149/4/2014 5:41:44 AM 3

    Why Triggers?

    Maintaining complex integrity constraints not possible through declarative

    constraints enabled at table creation

    Auditing information in a table by recording the changes made and who made

    them

    Automatically signaling other programs that action needs to take place when

    changes are made to a table

    Publishing information about various events in a publish subscribe

    environment

  • 8/11/2019 DAY 4 Triggers

    4/34

    PL/SQL Training9/4/20149/4/2014 5:41:44 AM 4

    Database Events

    Table

    Update

    Trigger

    Insert

    Trigger

    Update

    Trigger

    Update

    Insert

    Delete

    DATABASE

    User A User ALOGGING IN LOGGING OUT

    Database Up

    Database DOWN

    Errors

    User B LOGGING IN User BLOGGING OUT

  • 8/11/2019 DAY 4 Triggers

    5/34

    PL/SQL Training9/4/20149/4/2014 5:41:44 AM 5

    Trigger Types

    DML Triggers

    DML Trigger is fired by a DML statement, and the type of statement determines the type

    of DML Trigger

    DML Triggers are classified based on

    Level --Row Level (fires for each row) /Statement Level

    Timing --Before /After

    Statement --Insert /Update/ Delete

    Total --2X2X3=12 Types of DML Triggers

    Instead of Triggers

    Instead of Triggers are defined on views ONLY

    Unlike DM Trigger which executes in addition to the DML operation, an Instead of Trigger

    will execute instead of the DML statement that fired it

    These should be ROW LEVEL ONLY

    System triggers

    System Trigger fires when a system event, such as STARTUP/SHUTDOWN occurs

    System Trigger will be fired on DDL operations

  • 8/11/2019 DAY 4 Triggers

    6/34

    PL/SQL Training9/4/20149/4/2014 5:41:44 AM 6

    Trigger Syntax

    Syntax:

    CREATE [OR REPLACE] TRIGGER trigger_name

    { BEFORE / AFTER/INSTEAD OF} trigger_event

    referencing_clause

    [FOR EACH ROW]

    [WHEN trigger_condition]

    trigger_body

    trigger_name :is the name of trigger to be created

    trigger_event :specifies the event that fires the

    trigger

    referencing_clause :is used to refer to the data in the row

    currently being modified with a different name

    trigger_condition :if present will be evaluated first.trigger_body will be executed only when

    trigger_condition is

    evaluates to TRUE

    trigger_body :The business logic to be executed

    Note:The trigger body cannot exceed 32K

  • 8/11/2019 DAY 4 Triggers

    7/34PL/SQL Training9/4/20149/4/2014 5:41:44 AM 7

    Trigger Example

    create or replacetrigger bfrupdEMPTRI

    before update on EMPTRI

    BEGINinsert into TRI_TST values(SRITST.NEXTVAL, SYS.LOGIN_USER, sysdate);

    END;

  • 8/11/2019 DAY 4 Triggers

    8/34PL/SQL Training 9/4/20149/4/2014 5:41:44 AM 8

    Creating DML Triggers

    Category Values Description

    Statement INSERT/UPDATE/DELETE

    Defines which kind of DML Statement causesthe trigger to fire

    Timing Before /After Defines whether the trigger fires before areAfter the statement is executed

    Level Row / Statement If the trigger is row level, it fires once for eachrow affected by the triggering statement

    If the trigger is statement level, it fires onceeither before or after the statement

    A row level trigger is identified by the FOREACH ROW clause in trigger definition

    A Table can have any number of triggers define on it, including more

    than one of a given DML type

  • 8/11/2019 DAY 4 Triggers

    9/34PL/SQL Training 9/4/20149/4/2014 5:41:44 AM 9

    Row level Trigger Demo

    create or replace trigger bfrupdEMPTRIr before update on EMPTRI

    for each row

    BEGINinsert into TRI_TST values(SRITST.NEXTVAL, SYS.LOGIN_USER, sysdate);

    END;

  • 8/11/2019 DAY 4 Triggers

    10/34PL/SQL Training 9/4/20149/4/2014 5:41:44 AM

    Order of DML Trigger Firing

    Executes the Before Statement Triggers if present

    For Each Row affected by the statement

    Executes before Row level triggers if present

    Execute the Statement (i.e trigger body)

    Execute the After statement row level triggers if present

    Executes the After Statement Level Triggers, if present

  • 8/11/2019 DAY 4 Triggers

    11/34PL/SQL Training

    9/4/20149/4/2014 5:41:44 AM 11

    Correlation Identifiers (Row Level Triggers Only)

    A row level trigger fires once per row processed by the triggering statement.

    Inside the trigger we can access the data in the row that is being currently being processes

    This is done through two correlation identifiers :new, :old

    A correlation identifier is a special kind of PL/SQL bind variable

    PL/SQL compiler will treat them as records type

    triggering_table%ROWTYPE

    Thus, :new.field is valid only if fieldis a field in triggering table

    TriggeringStatement

    :old :new

    INSERT Undefined All fields are NULL Values that will be inserted when thestatement is complete

    UPDATE Original values for the row beforethe update

    New values that will be updated when thestatement is complete

    DELETE Original Values before the row isdeleted

    Undefined all fields are Null

  • 8/11/2019 DAY 4 Triggers

    12/34PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Correlation Identifiers

    create table TRI_NEWOLD (old varchar2(20), new varchar2(20))

    create or replace trigger aftupdEMPTRI

    after update on EMPTRI

    for each rowBEGIN

    insert into TRI_NEWOLD values(:old.ename, :new.ename);

    END;

    select empno, ename from emp where deptno=10;

    update emptri set ename=ename||'new' where deptno=10;

    select * from TRI_NEWOLD;

  • 8/11/2019 DAY 4 Triggers

    13/34PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Correlation Identifiers Clause Demo Output

  • 8/11/2019 DAY 4 Triggers

    14/34PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Trigger Clauses

    Referencing Clause:This clause is used to specify a different name for :oldand

    :new.

    WHEN Clause:Is valid for Row Level Triggers ONLY. If present the trigger body

    will be executed only for those rows that meet the condition specified by the WHEN

    Clause

    Trigger Predicates:

    INSERTING, UPDATING and DELETING:

    Determines what operation is being done inside trigger

    These are Boolean type

    Predicate Behavior

    INSERTING TRUE if the triggering statement is an INSERT; FALSE otherwise

    UPDATING TRUE if the triggering statement is an UPDATE; FALSE otherwise

    DELETING TRUE if the triggering statement is an DELETE; FALSE otherwise

  • 8/11/2019 DAY 4 Triggers

    15/34PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Referencing Clause

    truncate table TRI_NEWOLD;

    create or replace trigger aftupdEMPTRI

    after update on EMPTRI

    referencing old as ABC new as XYZ

    for each row

    BEGINinsert into TRI_NEWOLD values(:ABC.ename, :XYZ.ename);

    END;

    update EMPTRI set ename=ename||'X' where deptno=10;

    select * from TRI_NEWOLD;

  • 8/11/2019 DAY 4 Triggers

    16/34PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Referencing Clause

  • 8/11/2019 DAY 4 Triggers

    17/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Trigger Predicates Demo

    drop trigger aftupdEMPTRI;

    create or replace trigger aftupdEMPTRI

    after update on EMPTRI

    for each row

    BEGIN

    IF INSERTINGthen

    insert into TRI_NEWOLD(OLD) values('Insertion Oprn');ELSIF UPDATINGTHEN

    insert into TRI_NEWOLD(OLD) values('Update Oprn');

    ELSE

    insert into TRI_NEWOLD(OLD) values('Delete Oprn');

    END IF;

    END;

    updateEMPTRI set sal=3950 where empno=7369;

    select * from TRI_NEWOLD;

  • 8/11/2019 DAY 4 Triggers

    18/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Trigger Predicates Demo Output

  • 8/11/2019 DAY 4 Triggers

    19/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    WHEN Clause

    Valid for ROW Level Triggers ONLY

    drop trigger aftupdEMPTRI;

    create or replace trigger aftupdEMPTRI

    after update on EMPTRI

    for each rowwhen (old.sal > 2000)

    BEGIN

    insert into TRI_NEWOLD values(:old.sal, :new.sal);

    END;

  • 8/11/2019 DAY 4 Triggers

    20/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Instead of Triggers

    These triggers fire instead of a DML operation

    These are defined only on Views

    Instead of triggers used in two cases

    To allow a view that would not otherwise not to be modifiable to be modified

    To modify the columns of a nested table column in a view

  • 8/11/2019 DAY 4 Triggers

    21/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Modifiable Vs Non-Modifiable Views

    A modifiable view is one against which we can issue a DML statement

    A view is modifiable if it does not contain any of the following

    Set operators (UNION, UNION ALL, MINUS)

    Aggregate functions (SUM, AVG, etc)

    GROUP BY, CONNECT BY, START WITH clauses

    The distinct operator

    Joins

    Exception:Some views with Joins also modifiable.

    A Join View is modifiable if the DML operation on it modifies only one base table a time and

    the DML statement meets the following conditions

    INSERT: The statement does not refer, implicitly or explicitly, to the columns of a non-

    key preserved table

    Update: The updated columns map to key preserved table

    Delete: There is exactly one key preserved table in the join

    Key Preserved Table:Atable is key preserved table if, after a join with another table,

    the keys in the original table are also keys in the resultant join

  • 8/11/2019 DAY 4 Triggers

    22/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    System Triggers

    System Triggers are two types

    DDL Events includes CREATE, ALTER, DROP Statements

    Database events includes STARTUP/SHUTDOWN of the server, logon/logoff os user and a

    Server Error

    Database Level events

    Schema Level events

    Syntax

    CREATE [OR REPLACE] TRIGGER [schema.]trigger_name

    {BEFORE/AFTER}

    {ddl_event_list|database_event_list}

    On {DATABASE|[schema.]SCHEMA}

    [when_clause]

    trigger_body;

    ddl_event_list:Is one or more DDL events separated by OR key word

    database_event_list:Is one or more database events separated by OR key word

    Note:No Database Event for TRUNCATE

  • 8/11/2019 DAY 4 Triggers

    23/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    SCHEMA Level Trigger Example

    Create Trigger Using SCHEMA Level Trigger

    Log oof to User

    Login to User again

    Log of User&

    Login again

    1

    2

    3

  • 8/11/2019 DAY 4 Triggers

    24/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    SCHEMA Level Trigger Example

    Only SYS, SYSDBA Users can create DATABASE Level Triggers

    Login AS SYSDBA

    Create the trigger

    Log off and Log IN

    drop trigger LogonAft;

    truncate table tabsys;

    create or replace trigger

    LogonAft

    after LOGON ON DATABASE

    BEGIN

    insert into

    scott.tabsys

    values(SYS.LOGIN_USER,

    sysdate);

    END;

  • 8/11/2019 DAY 4 Triggers

    25/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    System Events

    Event Timing Allowed Description

    STARTUP AFTER Fired when an Instance is started up

    SHUTDOWN BEFORE Fired when an Instance is shu down. This eventmay not fire if the database is shutdownabnormally

    SERVERERROR AFTER Fired whenever an error occurs

    LOGON AFTER Fired after a user has successfully connected tothe database

    LOGOFF BEFORE Fired at the start of logoff

    CREATE BEFORE/AFTER Fired before or after a schema object is created

    DROP BEFORE/AFTER Fired before or after a schema object is dropped

    ALTER BEFORE/AFTER Fired before or after a schema object is altered

  • 8/11/2019 DAY 4 Triggers

    26/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Database & Schema Trigger

    A system trigger can be defined at the database level or a schema level

    A database level trigger will fire whenever the triggering event occurs

    A schema level trigger will fire only when the triggering event occurs for the

    specified schema

    DATABASE /SCHEMA keywords determine the level for a given system trigger

    If schema is not specified with SCHEMA key word the it defaults to the schema that

    owns the trigger

  • 8/11/2019 DAY 4 Triggers

    27/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Event Attribute Functions

    These functions allows the trigger body to get information about the triggering event

    These functions are standalone PLSQL functions owned by SYS.

    When we are accessing these functions we must prefix them with SYS.

  • 8/11/2019 DAY 4 Triggers

    28/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Event Attribute Functions

    Attribute Function Datatype System EventApplicable For

    Description

    SYSEVENT VARCHAR2 All Events Returns the system event fired the trigger

    INSTANCE_NUM NUMBER All Events Returns the current instance number

    DATABASE_NAME VARCHAR2 All Events Returns the current Database name

    IS_SERVERERROR BOOLEAN SERVERERROR Takes an error number as an argument, and returns TRUE if the Oracleerror indicated is on the error stack

    SERVER_ERROR NUMBER SERVERERROR Takes a single Number argument. Returns the error at the position onthe error stack indicated by the argument. The position 1 is the top of the

    stack

    LOGIN_USER VARCHAR2 All events Returns the userid of the user that fired the trigger

    DICTIONARY_OBJ_TYPE

    VARCHAR2 CREATE, DROP,ALTER

    Returns the type of dictionary object on which the DDL operation thatfired the trigger occurred

    DICTIONARY_OBJ_NA

    ME

    VARCHAR2 CREATE, DROP,

    ALTER

    Returns the name of the dictionary object on which DDL operation that

    fired the trigger occurred

    DICTIONARY_OBJ_OWNER

    VARCHAR2 CREATE, DROP,ALTER

    Returns the owner of the dictionary object on which the DDL operationthat fired the trigger occurred

    DES_ENCRYPTED_PASSWORD

    VARCHAR2 CREATE or ALTERUSER

    Returns the DES encrypted password of the user being created oraltered

  • 8/11/2019 DAY 4 Triggers

    29/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    System Triggers Restrictions on WHEN Clause

    STARTUP and SHUTDOWN triggers cannot have any conditions

    SERVERERROR triggers can use the ERRNO test to check for a specific error only

    LOGON, LOGOFF triggers can check the user id or username with the USERID or

    USERNAME test

    DDL Triggers can check the type and name of the object being modified, and can check the

    user id and user name

    Trigger Names - - Namespace

    The Name Space for triggers is different from subprograms

    A Namespace is the set of legal identifiers available for use as names of an object.

    Procedures, Functions, Tables uses share namespace. Triggers uses a different one.

  • 8/11/2019 DAY 4 Triggers

    30/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Dropping & Disabling Triggers

    Dropping a Trigger

    DROP TRIGGER

    Disabling Trigger

    ALTER TRIGGER TRIGGER NAME {DISABLE|ENABLE}

    To Disable/Enable All the Triggers on a Table

    ALTER TABLE ENABLE/DISABLE All TRIGGERS

  • 8/11/2019 DAY 4 Triggers

    31/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Restrictions on Triggers

    Trigger should not issue any transaction control statements

    COMMIT/ROLLBACK/SAVEPOINT/ SET TRANSACTION

    PLSQL Compiler will allow these statements, but an error will be generated when trigger is

    fired

    Any procedures and functions that are called by the trigger body cannot issue transaction

    control statements (Unless they are also declared as autonomous )

    Trigger body cannot declare any LONG or LONG RAW variables.

    :new, :old cannot refer to a LONG, LONG RAW columns in the table

    Trigger body may reference and use LOB columns, but it will may not modify the values ofthe columns

  • 8/11/2019 DAY 4 Triggers

    32/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Trigger Privileges

    System Privilege Description

    CREATE TRIGGER Allows the grantee to create a trigger in his own schema

    CREATE ANYTRIGGER

    Allows the grantee to create triggers in any schema except SYS. It isnot recommended to create triggers on data dictionary tables

    ALTER ANY TRIGGER Allows the grantee to enable, disable or compile database triggers inany schema

    DROP ANY TRIGGER Allows the grantee to drop database triggers in any schema exceptSYS

    ADMISITER

    DATABASE TRIGGER

    Allows the grantee to create or alter a system trigger on the database.

    The grantee must also have either CREATE TRIGGER or CREATEANY TRIGGER

  • 8/11/2019 DAY 4 Triggers

    33/34

    PL/SQL Training 9/4/20149/4/2014 5:41:45 AM

    Data Dictionary

    Trigger source code will be stored in the Table USER_TRIGGERS

    USER_TRIGGERS Table

    SQL> desc USER_TRIGGERS;---------------------------------------------------------------------------

    Name Null? Type

    ---------------------------------------------------------------------------

    TRIGGER_NAME VARCHAR2(30)

    TRIGGER_TYPE VARCHAR2(16)

    TRIGGERING_EVENT VARCHAR2(227)

    TABLE_OWNER VARCHAR2(30)

    BASE_OBJECT_TYPE VARCHAR2(16)

    TABLE_NAME VARCHAR2(30)

    COLUMN_NAME VARCHAR2(4000)

    REFERENCING_NAMES VARCHAR2(128)

    WHEN_CLAUSE VARCHAR2(4000)

    STATUS VARCHAR2(8)

    DESCRIPTION VARCHAR2(4000)

    ACTION_TYPE VARCHAR2(11)

    TRIGGER_BODY LONG

    ---------------------------------------------------------------------------

  • 8/11/2019 DAY 4 Triggers

    34/34

    Srinivas Nagula

    Subprograms