Triggers

A trigger is a procedure fired automatically when a DML statement (INSERT, UPDATE, or DELETE) is run against a certain table. A row-level trigger runs once for every row affected. A statement-level trigger runs once for all the rows. A row-level trigger has access to the old and new column values when the trigger fires.

Creating a Trigger

You create a trigger using the CREATE TRIGGER statement. The simplified syntax for the CREATE TRIGGER statement:


CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF | FOR} trigger_event
ON table_name
[FOR EACH ROW]
[WHEN trigger_condition]]
BEGIN
   trigger_body
END trigger_name;

ItemDescription
BEFOREthe trigger fires before the triggering event is performed.
AFTERthe trigger fires after the triggering event is performed.
INSTEAD OFthe trigger fires instead of performing the triggering event.
FORcreates a compound trigger consisting of up to four sections in the trigger body.
trigger_eventthe event that causes the trigger to fire.
table_namethe table that the trigger references.
FOR EACH ROWthe trigger is a row-level trigger. If you omit FOR EACH ROW,the trigger is a statement-level trigger.
trigger_conditiona Boolean condition that limits when a trigger actually runs its code.
trigger_bodycontains the code for the trigger.
 
CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,
                  ENAME VARCHAR2(10),
                  JOB VARCHAR2(9),
                  SAL NUMBER(7, 2),
                  DEPTNO NUMBER(2));

INSERT INTO EMP VALUES (1, 'SMITH', 'CLERK',     800,    20);
INSERT INTO EMP VALUES (2, 'ALLEN', 'SALESMAN', 1600,    30);
INSERT INTO EMP VALUES (3, 'WARD',  'SALESMAN', 1250,    30);
INSERT INTO EMP VALUES (4, 'JONES', 'MANAGER',  2975,    20);

CREATE TABLE EMP_AUDIT (EMPNO NUMBER(4) NOT NULL,
                  old_SAL NUMBER(7, 2),
                  new_SAL NUMBER(7, 2));


CREATE TRIGGER before_salary_update
BEFORE UPDATE OF sal
ON emp
FOR EACH ROW WHEN (new.sal < old.sal * 0.75)
BEGIN
   dbms_output.put_line('id = ' || :old.empno);
   dbms_output.put_line('Old:' || :old.sal);
   dbms_output.put_line('New:' || :new.sal);
   dbms_output.put_line('The sal reduction is more than 25%');
   INSERT INTO emp_audit (empno, old_sal, new_sal) 
          VALUES (:old.empno, :old.sal, :new.sal);
END before_salary_update;
/

SET SERVEROUTPUT ON

UPDATE emp SET sal = sal * .7;


SELECT * FROM emp_audit;
  
Home »
Oracle »
PL/SQL » 

Triggers:
  1. Triggers
  2. Getting Information on Triggers
  3. Disabling and Enabling a Trigger
  4. Dropping a Trigger
Related: