You are on page 1of 2

Triggers

A trigger is a stored subprogram associated with a table, view, or event. The trigger can be invoked
once, when some event occurs, or many times, once for each row affected by an INSERT, UPDATE, or
DELETE statement. The trigger can be invoked before or after the event.
The trigger in example is invoked whenever salaries in the employees table are updated. For each
update, the trigger writes a record to the emp_audit table.
Example:
Creating a Trigger
SQL> CREATE TABLE emp_audit (
2

emp_audit_id NUMBER(6),

up_date

DATE,

new_sal

NUMBER(8,2),

old_sal

NUMBER(8,2)

6 );
Table created.
SQL> CREATE OR REPLACE TRIGGER audit_sal
2
3
4

AFTER UPDATE OF salary


ON employees
FOR EACH ROW

5 BEGIN
6
7

INSERT INTO emp_audit


VALUES(:old.employee_id,SYSDATE,:new.salary,
:old.salary);

8 END;
9 /
Trigger created.
SQL> update employees set salary=5000
2 where salary < 3000;
24 rows updated.

SQL> select * from emp_audit;


EMP_AUDIT_ID UP_DATE

NEW_SAL

OLD_SAL

------------ --------- ---------- ---------116 25-JUL-09

5000

2900

117 25-JUL-09

5000

2800

EMP_AUDIT_ID UP_DATE

NEW_SAL

------------ --------- ---------- ---------135 25-JUL-09

5000

2400

136 25-JUL-09

5000

2200

..

24 rows selected.

OLD_SAL

You might also like