Professional Documents
Culture Documents
Triggers
Triggers
The above syntax shows the different optional statements that are
present in trigger creation.
BEFORE/ AFTER will specify the event timings.
INSERT/UPDATE/LOGON/CREATE/etc. will specify the event for which
the trigger needs to be fired.
ON clause will specify on which object the above-mentioned event is
valid. For example, this will be the table name on which the DML event
may occur in the case of DML Trigger.
Command "FOR EACH ROW" will specify the ROW level trigger.
WHEN clause will specify the additional condition in which the trigger
needs to fire.
The declaration part, execution part, exception handling part is same as
that of the other PL/SQL blocks. Declaration part and exception
handling part are optional.
To delete a trigger:
Syntax:
DROP TRIGGER trigger_name.
Types of Triggers
Q. State the use of database trigger and also list types of trigger.
Use of trigger
Trigger: A trigger is a stored procedure in database which automatically invokes whenever a
special event in the database occurs. A trigger can be invoked when a row is inserted into a
specified table or when certain table columns are being updated. Triggers are written to be
executed in response to any of the following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
Database definition (DDL) statements (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is
associated.
Triggers can be written for the following purposes –
Generating some derived column values automatically
Enforcing referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions
Types of trigger
DML Triggers
DDL Triggers
Logon Triggers
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger
will display the salary difference between the old values and new values −
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table −
Because this is a new record, old salary is not available and the above result comes as null. Let
us now perform one more DML operation on the CUSTOMERS table. The UPDATE statement
will update an existing record in the table
UPDATE customerstab
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500
1 row(s) updated.