Oracle Concepts
Selvaraj V Anna University Chennai. Chennai – 25.
Oracle Triggers Triggers are actions defined on tables. 1. Why are triggers required? If we want to perform certain actions whenever an insert/update/delete happens on a table, we could achieve this by using a trigger. Remember, only these 3 DMLs - Insert/Update/delete could fire a trigger. Truncate or drop or create or any other commands could not fire a trigger on a particular table. 2. Different types of Classification for Triggers: First type of classification ::
a. Row Level Trigger: For each row affected by the Insert/Update/Delete operation, the trigger is fired and thus the action associate with it. Delete from emp where deptno=30;
-- deletes 10 records
For eg: If you want to log all the Employee Ids if they gets deleted, you could create an After Delete Row Level Trigger such that for each ID getting deleted they could be inserted into an Audit Table. So, for the above delete operation the trigger is fired 10 times. b. Statement Level Trigger: The trigger will be fired only once for the Insert/Update/Delete opearion happened on a table. For eg: Upda Update te emp emp set set sal= sal=sa sal+ l+10 1050 50 wher here dep deptn tno= o=30 30;;
--Up --Upda date te 30 recor ecords ds
This update statement updates 30 records in a single update operation. But if the Trigger on table Emp statement level, it will fire the trigger only once.
Second type of classification:: Before and After triggers Before Trigger
: The trigger gets fired before an Insert/Update/Delete
operation happens on the table. After Trigger
: The trigger gets fired after an Insert/Update/Delete operation
happens on the table. Based on the 2 types of classifications, we could have 12 types of triggers. Before Insert row level After Insert row level Before Delete row level After Delete row level Before Update row level After Update row level Before Insert Statement Level After Insert Statement Level Before Delete Statement Level After Delete Statement Level Before Update Statement Level After Update Statement Level Frequently Asked Questions: 1. What is a Mutating table error (MTE)? Oracle manages read consistent view of data. The error occurs when a rowlevel trigger accesses the same tables on which it is based while executing. 2. How to get rid of Mutating table error? In the Row level trigger we cannot update, insert or select from the mutating table. So we create a package with a collection type in it. Then in the Row level trigger store the values (to be used) into the Collection type. Then add a Statement level trigger to the same table which calls the Package uses the stored data to do the data manipulation. Eg:
create pa package pa pack1 is arr VARRAY(100); end;
create or replace trigger row_trg1 before update on table1 for each row begin pack1.arr(0):= :old.col1; ----end; create or replace trigger stmt_trg1 before update on table1 declare v_col number; begin v_col:= pack1.arr(0); ----
end; 3. Maximum Trigger size in Oracle
:
32k (but functions, procedures etc could be called inside) 4. Can we create trigger on views? No. Eg: Eg:
But we can use INSTEAD OF Triggers
crea create te or repl replac ace e tri trigg gger er trg_ trg_lo logo gon n Instead of update on view_v1 For each row Begin
-- can cal calll a procedure o orr a ffu unction to too.
End; / 5. Can we do commit or rollback in a trigger? No Exce Except ptio ion n commit or rollback
: If If the the trig trigge gerr is is an an AUT AUTON ONOM OMOU OUS S TRA TRANS NSAC ACTI TION ON we we can can
6. When a table or view is dropped, what happens to the associated triggers? Triggers associated to the dropped Tables, Views also gets DROPPED 7. What is an INSTEAD OF Trigger in Oracle? Views cannot have triggers. So, when someone tries to update a view, you can re-direct the data to the underlying table using an INSTEAD OF trigger. Eg:
create or replace trigger ins_trigger INSTEAD OF update on emp_view For each row Begin if :new.sal<:old.sal then update emp set sal=:old.sal where
empno=:new.empno; else update emp set sal=:new.sal where empno=:new.empno; end if; End; *When INSTEAD OF trigger is written, even if the view is directly updateable, it updates using the trigger only. 8. Does Truncate on a table fires a Trigger? No. A Truncate table operation won’t fire the trigger even if it is defined as a delete trigger. Only a delete operation could fire a trigger and when the Trigger is a Delete trigger.
Database Triggers A database triggers is stored PL/SQL program unit associated with a specific database table or view. The code in the trigger defines the action the database needs to perform whenever some database manipulation (INSERT, UPDATE, DELETE) takes place. Unlike the stored procedure and functions, which have to be called explicitly, the database triggers are fires (executed) (executed) or called implicitly implicitly whenever whenever the table is affected by any of the above said DML operations.
Till oracle 7.0 only 12 triggers could be associated with a given table, but in higher versions of Oracle there is no such limitation. A database trigger fires with the privileges of owner not that of user A database trigger has three parts 1. A tri trigg gger ering ing even eventt 2. A trigg trigger er cons constra traint int (Opti (Optiona onal) l) 3. Trig Trigge gerr act actio ion n
A triggering event can be an insert, update, or delete statement or a instance shutdown or startup etc. The trigger fires automatically when any of these events occur A trigger constraint specifies a Boolean expression that must be true for the trigger to fire. This condition is specified using the WHEN clause. The trigger action is a procedure that contains the code to be executed when the trigger fires.
Types of Triggers The following are the different types of triggers. Row triggers and statement triggers A Row trigger fires once for each row affected. It uses FOR EACH ROW clause. They are useful if trigger action depends on number of rows affected. Statement Trigger fires once, irrespective of number of rows affected in the table. Statement triggers are useful when triggers action does not depend on Before and afterTriggers While While defini defining ng the trigge triggerr we can specif specify y wheth whether er to perfor perform m the trigge triggerr action (i.e. execute trigger body) before or after the triggering statement. BEFORE and AFTER triggers fired by DML statements can only be defined on tables. BEFORE triggers The trigger action here is run before the trigger statement. AFTER triggers The trigger action here is run a fter the trigger statement. INSTEAD of Triggers provide a way of modifying views that can not be modified directly using DML statements. LOGON triggers fires after successful logon by the user and LOGOFF trigger fires at the start of user logoff.
Points to ponder •
A trigger cannot include COMMIT, SAVEPOINT and ROLLBACK.
•
We can use only one trigger of a particular type .
•
A table can have any number of triggers.
•
We use correlation names :new and :old can be used to refer to data in command line
and data in table respectively.
Triggers on DDL statements DDL trigger are of the following types BEFORE CREATE OR AFTER CREATE trigger is fired when a schema object is created. BEFO BE FORE RE OR AFTE AFTER R ALTE ALTER R trig trigge gerr is fire fired d when when a sche schema ma obje object ct is alte altere red. d. BEFORE OR AFTER DROP trigger is fired when a schema object is dropped. A trigger can be enabled means can be made to run or it can disabled means it cannot run. A trigger is automatically enabled when it is created. We need reenable trigger for using it if it is disabled. To enable or disable a trigger using ALTER TRIGGER command, you must be owner of the trigger or should have ALTER ANY TRIGGER privilege. To create a trigger you must have CREATE TRIGGER privilege, which is given to as part of RESOURCE privilege at the time of user creation. Following figures give more understanding about triggers