Sub topic 3
Writing Your First Trigger with CREATE OR REPLACE TRIGGER
Prerequisites and the Basic Idea
This chapter assumes you know basic SQL statements, PL/SQL blocks, variables, IF statements, and transactions. You should also be familiar with tables and sequences.
A database trigger is a stored PL/SQL program that Oracle runs automatically when a specified event occurs. The event might be an INSERT, UPDATE, or DELETE on a table. You do not call the trigger directly.
Use CREATE OR REPLACE TRIGGER to create a trigger or replace an existing trigger with the same name. Replacing a trigger is useful while developing because you can edit and compile it repeatedly without dropping it first.
Trigger Syntax
A row trigger has these main parts:
- The trigger name follows
TRIGGER. - The timing says when the trigger runs:
BEFOREorAFTERthe event. - The event says what causes it to run.
FOR EACH ROWmakes it run once for every affected row.- The body contains PL/SQL statements between
BEGINandEND.
CREATE OR REPLACE TRIGGER employees_bi
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF :NEW.employee_id IS NULL THEN
:NEW.employee_id := employees_seq.NEXTVAL;
END IF;
:NEW.created_at := SYSTIMESTAMP;
END employees_bi;
/This example assumes that the employees table has employee_id and created_at columns, and that employees_seq is an existing sequence.
The trigger runs before each inserted row is stored. If the statement inserts five rows, the trigger body runs five times. When employee_id is missing, the trigger assigns the next sequence value. It also assigns the current timestamp to created_at.
The slash on the line after END is a client command. Tools such as SQL*Plus and SQLcl use it to submit the completed PL/SQL unit to Oracle. It is not part of the trigger's stored source.
Selecting Timing and Level
Choose BEFORE when the trigger must validate or change values before Oracle stores them. Choose AFTER when the row has already been changed and the trigger should perform a related action, such as writing an audit record.
A statement trigger runs once for the entire SQL statement. A row trigger uses FOR EACH ROW and runs once per affected row. Without FOR EACH ROW, the trigger is a statement trigger.
The event can contain more than one operation:
CREATE OR REPLACE TRIGGER employees_change_notice
AFTER INSERT OR UPDATE OR DELETE ON employees
BEGIN
DBMS_OUTPUT.PUT_LINE('Employees changed');
END employees_change_notice;
/This trigger runs once after each INSERT, UPDATE, or DELETE statement, regardless of how many rows the statement affects.
Exercise
What is the difference between a row trigger and a statement trigger?
Show answer
A row trigger runs once for each affected row; a statement trigger runs once for the whole SQL statement.