You are on page 1of 20

Triggers

IF-2305 Pemrograman Basis Data Tahun Ajaran 2011-2012

9/15/2011 1

Triggers
Triggers is a procedure that is automatically invoked by the DBMS in response to specified changes to the database A trigger description contains three part: Event: A change to the database that activates the trigger The sorts of events allowed are usually insert, delete or update to a particular relation Condition: A query or test that is run when the trigger is activated If the condition does not hold, then nothing else associated with the trigger happens in response to this event. Action: A procedure that is executed when the trigger is activated and its condition is true The action could be any sequence of database operations, perhaps even operations not connected in any way to the triggering event

9/15/2011 2

Triggers vs Constraints
Triggers are only awakened when certain events, specified by the database programmer, occur. Instead of immediately preventing the event that awakened it, a trigger tests a condition. If the condition of the trigger is satisfied, the action associated with the trigger is performed by the DBMS.

9/15/2011 3

Principal Features
The action may be executed either before or after the triggering event. The action can refer to both old and/or new values of tuples that were inserted, deleted, or updated in the event that triggered the action. Update events may be limited to a particular attribute or set of attributes. A condition may be specified by a WHEN clause; the action is executed only if the rule is triggered and the condition holds when the triggering event occurs. The programmer has an option of specifying that the action is performed either: Once for each modified tuple, or Once for all the tuples that are changed in one database operation.

9/15/2011 4

Example
CREATE TABLE T4 (a INTEGER, b CHAR(10)); CREATE TABLE T5 (c CHAR(10), d INTEGER); CREATE TRIGGER trig1 } declaration AFTER INSERT ON T4 } event REFERENCING NEW AS newRow } the tuple after the update FOR EACH ROW } executed once for each updated tuple WHEN (newRow.a <= 10) } condition BEGIN INSERT INTO T5 VALUES(:newRow.b, :newRow.a); action END trig1; . run; What does this trigger do?

9/15/2011 5

Trigger Layout
BEFORE: the WHEN condition is tested before the triggering event, that is, before the modification that awakened the trigger has been made to the database If the condition is true, then the action of the trigger is executed. The event that awakened the trigger is executed, regardless of whether the condition is true. AFTER: the action is executed after the triggering event The OF keyword: optional for UPDATE defines the event to be only an update of the attribute(s) listed after the keyword OF The WHEN clause is optional. If it is missing, then the action is executed whenever the trigger is awakened.

9/15/2011 6

Trigger Layout
Action surrounded by BEGIN.. .END and separated by semicolons FOR EACH ROW: row-level trigger executed once for each tuple FOR EACH STATEMENT: statement-level trigger executed once whenever a statement of the appropriate type is executed no matter how many rows - zero, one, or many - it actually affects

9/15/2011 7

Trigger Syntax in Oracle


CREATE [OR REPLACE] TRIGGER <trigger_name> {BEFORE|AFTER} {INSERT|DELETE|UPDATE} ON <table_name>

[REFERENCING [NEW AS <new_row_name>] [OLD AS <old_row_name>]] [FOR EACH ROW [WHEN (<trigger_condition>)]] <trigger_body>

Basic triggers syntax in Oracle is differs slightly from standard SQL syntax

9/15/2011 8

Trigger Syntax in Oracle


Basic triggers syntax in Oracle is differs slightly from standard SQL syntax Only for row-level triggers: The special variables NEW and OLD are available to refer to new and old tuples respectively. Note: In the trigger body, NEW and OLD must be preceded by a colon (":"), but in the WHEN clause, they do not have a preceding colon! See example below. The REFERENCING clause can be used to assign aliases to the variables NEW and OLD. A trigger restriction can be specified in the WHEN clause, enclosed by parentheses. The trigger restriction is a SQL condition that must be satisfied in order for Oracle to fire the trigger. This condition cannot contain subqueries. Without the WHEN clause, the trigger is fired for each row.

9/15/2011 9

Trigger Syntax in Oracle


The restrictions on <trigger_body> include: You cannot modify the same relation whose modification is the event triggering the trigger. You cannot modify a relation connected to the triggering relation by another constraint such as a foreign-key constraint.

9/15/2011 10

Example
SET SERVEROUTPUT ON CREATE TRIGGER CheckStar BEFORE INSERT ON StarsIn REFERENCING NEW AS newRow FOR EACH ROW BEGIN INSERT INTO MovieStar(name) VALUES (:newRow.StarName); DBMS_OUTPUT.PUT_LINE('New Star '||:newRow.StarName||'!!'); END CheckStar; What is the event, condition and action of this trigger? What does this trigger do?

9/15/2011 11

Example
SET SERVEROUTPUT ON CREATE TRIGGER StudioProduct AFTER INSERT ON Movie DECLARE m_length NUMBER := 0; BEGIN SELECT SUM(length) INTO m_length FROM Movie; DBMS_OUTPUT.PUT_LINE('We have '|| m_length ||' minutes of movies!!'); END StudioProduct; What is the event, condition and action of this trigger? What does this trigger do? What differentiate this trigger from the previous?

9/15/2011 12

Altering Triggers
To view a list of all defined triggers, use: SELECT trigger_name FROM user_triggers; For more details on a particular trigger: SELECT trigger_type, triggering_event, table_name, referencing_names, trigger_body FROM user_triggers WHERE trigger_name = '<trigger_name>'; To drop a trigger: DROP TRIGGER <trigger_name>; To disable or enable a trigger: ALTER TRIGGER <trigger_name> {DISABLE|ENABLE};

9/15/2011 13

Aborting Triggers with Error


Triggers can often be used to enforce contraints. The WHEN clause or body of the trigger can check for the violation of certain conditions and signal an error accordingly using the Oracle built-in function RAISE_APPLICATION_ERROR. The event that activated the trigger (insert, update, or delete) would be aborted. For example, the following trigger enforces the constraint Person.age >= 0:

9/15/2011 14

Aborting Triggers with Error


CREATE TABLE Person (age INT); CREATE TRIGGER PersonCheckAge AFTER INSERT OR UPDATE OF age ON Person FOR EACH ROW BEGIN IF (:new.age < 0) THEN RAISE_APPLICATION_ERROR(-20000, 'no negative age allowed'); END IF; END; . RUN;

9/15/2011 15

Aborting Triggers with Error


If we attempted to execute the insertion: INSERT INTO Person VALUES (-3); we would get the error message: ERROR at line 1: ORA-20000: no negative age allowed ORA-06512: at "MYNAME.PERSONCHECKAGE", line 3 ORA-04088: error during execution of trigger 'MYNAME.PERSONCHECKAGE' and nothing would be inserted. In general, the effects of both the trigger and the triggering statement are rolled back.

9/15/2011 16

Why Triggers Can Be Hard to Understand


The DBMS always checks whether some trigger is activated by the statement(s) that modifies the database If a statement activates more than one trigger, the DBMS typically processes all of them, in some arbitrary order The execution of the action part of a trigger could in turn activate another trigger In particular, execution of the action part of a trigger could again activate the same trigger (recursive triggers)

9/15/2011 17

Recursive Triggers
CREATE TRIGGER t1 AFTER INSERT ON table1 FOR EACH ROW BEGIN update_table_2(); END CREATE TRIGGER t2 AFTER UPDATE ON table2 FOR EACH ROW BEGIN insert_into_table_1(); END

9/15/2011 18

Constraints versus Triggers


A constraint prevents the data from being made inconsistent by any kind of statement A trigger is activated by a special kind of statement (e.g., an insert or delete statement) Triggers allow us to maintain database integrity in more flexible ways

9/15/2011 19

Other Uses of Triggers


Triggers can alert users to unusual events (as reflected in updates to the database) Triggers can generate a log of events to support auditing and security checks Triggers can be used to gather statistics on table accesses and modifications

9/15/2011 20

You might also like