Trigger in SQL
Syntax
CREATE [OR REPLACE ] TRIGGER Your_Trigger_Name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF Column_Name]
ON Table_Name
[REFERENCING OLD AS oldd NEW AS neww]
[FOR EACH ROW]
WHEN (your_condition)
DECLARE
your Declaration statements goes here
BEGIN
your Executable statements goes here
EXCEPTION
Exception related handling-statements
END;
Example
CREATE OR REPLACE TRIGGER display_speed_changes
BEFORE DELETE OR INSERT OR UPDATE ON tblm_riders
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
speed_diff number;
BEGIN
speed_diff := :NEW.speed - :OLD.speed;
dbms_output.put_line('Old speed: ' || :OLD.speed);
dbms_output.put_line('New speed: ' || :NEW.speed);
dbms_output.put_line('Speed difference: ' || speed_diff );
END;
INSERT INTO TBLM_RIDERS (ID,NAME,AGE,COUNTRY,SPEED)
VALUES (7, 'Hrithik', 27, 'INDIA', 190 );
Ouput
Old Speed:
New Speed: 190
Speed difference:
Here in this example whenever a DML operation will be performed on the tblm_riders table
It will fire this display_speed_changes trigger and it display the appropriate old_speed, new speed and the difference.
Points
Normally triggers are executed based on concurrences of Events.
Triggers execute when some events Happens (i.e. Insert, Update, Delete, Create, Alter, Drop, Transaction, Logon, Logoff, Startup, Shutdown etc)
Triggers can be used for Auditing
Triggers can be used for handling invalid transactions.
It can be used to fill some column values automatically.