Triggers & Active Data Bases
Triggers
• What is a trigger?
Trigger is like a procedure that is automatically invoked
by the DBMS in response to specified changes to data
base
Trigger is like a ‘Daemon that monitors a data base,
and is executed when the data base is modified in
a way that matches the event specification
A data base that has a set of associated triggers is
called an active data base
Trigger Parts
• Event
A change to data base that activates the trigger
• Restriction
A trigger restriction specifies a Boolean (logical) expression
that must be TRUE for the trigger to fire
• Action
A procedure that is executed when the trigger is activated.
Similar to stored procedures, a trigger action can contain
PL/SQL statements
Types of Triggers
• Row Triggers
A row trigger is fired each time the table is affected by
the triggering statement. If a triggering statement affects
no rows, a row trigger is not executed at all.
• Statement Triggers
A statement trigger is fired once on behalf of the
triggering statement, regardless of the number of
rows in the table that the triggering statement affects
(even if no rows are affected)
Trigger Timings
• Before Trigger
Execute the trigger action before the triggering statement.
Eliminate unnecessary processing of the triggering statement.
• After Trigger
AFTER triggers are used when you want the triggering statement
to complete before executing the trigger action
Trigger
CREATE or REPLACE TRIGGER cs348
after INSERT ON weatherforecast
FOR EACH ROW
WHEN (:new.temp>= 60)
BEGIN
DBMS_OUTPUT.PUT_LINE(‘NICE WEATHER’);
END cs348
/
Show error;
Triggers can be confusing
• Update table weatherforcast
T1 Fired
Before Update on weatherforcast
For each row
Begin
Insert into weatherforcast2 values (.. , ..);
END;
T2 Fired
Before Update on weatherforcast 2
For each row
Begin
Insert into weatherforcast3 values (.. , ..);
END;
Triggers
• What are the uses of triggers?
Flexible Management of integrity
ItemId quantity customerid unitprice ItemId unitprice
Trigger Fired
123 1 224 123 $440
ItemId quantity customerid unitprice
123 1 224 440
Log generation to support auditing & security
Prevent invalid transactions
Thank You
References
[1] http://thinkunix.net/unix/db/oracle/docs-7.3/DOC/server/doc/SCN73/ch15.htm
[2] Database Management Systems, (NOTE: Third Edition), by Raghu Ramakrishnan and J. Gehrke.
[3] http://infolab.stanford.edu/~ullman/fcdb/oracle/or-triggers.html