Вы находитесь на странице: 1из 42

By Muhammad Fahim Khan

By Nidhi Bhatnagar
Muhammad Fahim Khan

Objectives
 Trigger – Concept
 Trigger – Requirement
 Trigger - Uses
 Trigger – Types
 Referencing columns :OLD Vs :New
 Trigger – Important points
Muhammad Fahim Khan

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

Triggers – Concept

 Triggers are basically created and stored like


stored procedure in database.

 Once they are stored then they are automatically


compiled and called by database itself, under a
given condition or what we call as Triggering
Event.
Muhammad Fahim Khan

Triggers – Why
 Triggers provides support for following
activities in database:
– Validation : There are certain validations on table
and its data that we cannot provide using constraints
so 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 by
checking the balance in the Account master table.
Muhammad Fahim Khan

Triggers – Why

– Auditing: Triggers are automatically called when


some action happens on a table, so they can be used
to keep track for all the activities happening on a
table.

Eg:
Triggers can be written on a table emp, dept etc to
check and store the name of the person , date and
time of any operation and type of operation
happening on these tables in some other audit table .
Muhammad Fahim Khan

Triggers – Why

– Backup: Triggers can be used to automatically back


up some crucial data.

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

Triggers – Why

– Restrictions: Triggers can be used to impose


restriction or prohibit some operation under certain
conditions.

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

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

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

Triggers
Note :
In current session we will deal with DML
triggers only as they are used for table
level operations. Other trigger requires

4. Special privileges (DBA)


5. Not in the scope/expectation of the current
session
Muhammad Fahim Khan

Triggers – Syntax
CREATE [OR REPLACE] TRIGGER <TRIGGER_NAME>
{TRIGGERING_TIME}
{TRIGGERING_EVENT} ON <TABLE_NAME>
[FOR EACH ROW [WHEN (<TRIGGER_CONDITION>)] ]

DECLARE
<Variable_Declaration>
BEGIN
<CODE>
EXCEPTION
<Exception_Handlers>
END;
Muhammad Fahim Khan

Triggers – Syntax

 TRIGGERING_TIME
– Before : Specify before if database should
fire trigger (execute trigger) before triggering
event.

– After :Specify After if database should fire


trigger (execute trigger) after triggering event.
Muhammad Fahim Khan

Triggers – Syntax

 TRIGGERING_EVENT
– INSERT : If trigger should be fired or executed for Insert
operation.

– UPDATE : If trigger should be fired or executed for update


operation.

– DELETE :If trigger should be fired or executed for Delete


operation.
Muhammad Fahim Khan

Triggers – Syntax

 TABLE_NAME
– Name of the table for which trigger should execute.
Remember one DML trigger is always associated with
one table i.e. a same DML trigger cannot be written for
two different tables.

– Each trigger has a unique name.


Muhammad Fahim Khan

Triggers – Syntax
NOTE:
For practice of trigger examples.
Please make your own copy of table and
give different name for triggers preferably
with your own employee no else you will
over ride others persons triggers or two same
type of triggers on same table will cause
ambiguity and errors.
Muhammad Fahim Khan

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 row


level 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 statement
level trigger , it can be some query etc but not a sub-query
Muhammad Fahim Khan

Triggers – Syntax
 ROW 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 be
executed automatically by oracle.

Update Emp Set Sal = Sal + 500 ;

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

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

– If we want trigger to execute once before every row the above


statement or query will update then row level trigger i.e. with for
each row.
Muhammad Fahim Khan

Triggers – Syntax

 Mostly Row level is used for DML Triggers.

 For Validation , Backup , Auditing , Restriction etc


row level can be used.

 Statement level mostly is used for Auditing purposes


only.
Muhammad Fahim Khan

Triggers – Syntax

 DECLARE : Declaring local variables for the trigger.

 BEGIN : Contains the actual code for the trigger to


execute whenever triggering event happens.

 EXCEPTION: Exception or Error handling code.

 Basically these are same as normal block of PL SQL


Muhammad Fahim Khan

Trigger – Important

 Transaction control statements like Commit , Rollback


etc are not allowed in trigger.

 Create , Alter and Drop (DDL) statements are not


allowed in trigger.

 Insert , Update and Delete (DML) inside the trigger


code is allowed but only on tables other then the table
on which trigger itself is written.
Muhammad Fahim Khan

Trigger – Important

 Select query inside the trigger code on all tables is


allowed but query on the table on which trigger is
written can cause some problems , precautions should
be taken.

 Calling procedure , functions and packages inside


trigger is allowed but those procedures , functions and
packages should not contain any commit or rollback
statements.
Muhammad Fahim Khan

Trigger – Important
 Mutating Table : "Mutating" means "changing".
A mutating table is a table that is currently being
modified by an update, delete, or insert statement. When
a trigger tries to refer a table that is in state of flux (being
changed), it is considered "mutating" and raises an error
 Another way this error can occur is if the trigger has
statements to change the primary, foreign or unique key
columns of the table off which it fires. If we write some
code in trigger that can cause ambiguity with that table :
Example If we write a Insert query on the table in a
Insert trigger of that table itself which is not allowed then
at runtime it will give Mutation error.
Muhammad Fahim Khan

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 on
which the trigger is written.

 However you can write Insert , Update and


Delete query on other tables in the trigger
code.
Muhammad Fahim Khan

:OLD and :NEW

 Inside the trigger code since we cannot refer to the


table on which trigger is written directly so if we want
to check or change or verify the value in some column
of that table we can used :OLD and : NEW.

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


Muhammad Fahim Khan

:OLD and :NEW

 :OLD and :NEW refers to the row of the table on


which 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

:OLD and :NEW

 :OLD Vs :NEW

 In case of INSERT new data comes to table so we can refer to the


columns 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 the
trigger with :OLD.

 :NEW is invalid in Delete triggers.


Muhammad Fahim Khan

:OLD and :NEW

 :OLD Vs :NEW

 In case of UPDATE old data is modified with new


data so we can refer to the columns of that row of the
table 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 that


row.
Muhammad Fahim Khan

:OLD :NEW

<NULL> or Invalid :NEW.Col_Name


INSERT

:OLD.Col_Name :NEW.Col_Name
UDATE

:OLD.Col_Name <NULL> or Invalid


DELETE
Muhammad Fahim Khan

:OLD and :NEW

 Example : In dept table there is one record


Deptno Dname Loc
10 Admin Pune

 Suppose there is a update trigger on this table then we


can 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

: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

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

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

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 following


order.

– 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

Trigger – Important

 Row level is executed one time each for each row.

 Statement level only once for one query.


Muhammad Fahim Khan

Trigger – Important

 However on same table you cannot have


exactly two same type of triggers , they can
cause problems i.e. Two triggers on emp both
before update row level ,can cause errors.

 As table will not understand which one to


execute for each row before update happens.
Muhammad Fahim Khan

Trigger – Important

 Triggers are one of the important and


very excellent feature of Oracle PL SQL
but should be used properly as it slows
down the speed of DML operations.
Muhammad Fahim Khan

Example
 Create 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

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 where
table_name = ‘EMP_ESG';
Muhammad Fahim Khan

Disable/Enable TRIGGERS

 To disable or enable a trigger: To see the


structure

Alter trigger <trigger_name> {disable|


enable};

Example:
Alter Trigger Emp_Up_1 Disable;
Alter Trigger Emp_Up_1 Enable;
Muhammad Fahim Khan

Deleting TRIGGERS

 To delete trigger

Drop trigger <trigger_name>;

Example:
Drop Trigger Emp_Up_1;
Muhammad Fahim Khan

Thank you !!

Next Session:
Object types in
Oracle

Вам также может понравиться