Triggers
• A trigger is a set of SQL statements that reside in system memory with
unique names. It is a specialized category of stored procedure that is
called automatically when a database server event occurs. Each trigger
is always associated with a table.
• A trigger is called a special procedure because it cannot be called
directly like a stored procedure. The key distinction between the trigger
and procedure is that a trigger is called automatically when a data
modification event occurs against a table. A stored procedure, on the
other hand, must be invoked directly.
• The following are the main characteristics that distinguish triggers from
stored procedures:
• Triggers have no chance of receiving parameters.
• A transaction cannot be committed or rolled back inside a trigger.
Syntax of Triggers
• Create [or replace] Trigger trigger-
name
• {before | after}
• { insert [or] | update [or] |delete }
• On table_name
• [for each row]
• DECLARE
• Declaration statements
• Begin
• Executable-statements
• END;
• Create or replace an existing
trigger with the trigger name
• This specifies when the trigger
will be executed
• This specifies the DML
operations
• This specifies the name of the
table associated with the trigger
• This specifies the row level
trigger, i.e the trigger will be
executed for each row being
affected. Otherwise the trigger
will execute just once when the
sql statement is executed,
which is called a table level
trigger.
When we use triggers?
• Triggers will be helpful when we need to execute
some events automatically on certain desirable
scenarios. For example, we have a constantly
changing table and need to know the
occurrences of changes and when these changes
happen. If the primary table made any changes
in such scenarios, we could create a trigger to
insert the desired data into a separate table
Types of SQL Server Triggers
• We can categorize the triggers in SQL Server in mainly three
types:
• Data Definition Language (DDL) Triggers
• Data Manipulation Language (DML) Triggers
• Logon Triggers
Following are types of trigger
• Statement-level triggers
• A statement-level trigger is fired whenever a trigger event
occurs on a table regardless of how many rows are affected.
In other words, a statement-level trigger executes once for
each transaction.
• Row-level Triggers
• Row-level triggers fires once for each row affected by the
triggering event such as INSERT, UPDATE, or DELETE.
DDL Triggers
• DDL triggers are fired in response to the DDL events, such
as CREATE, ALTER, and DROP statements. We can create
these triggers at the database level or server level,
depending on the type of DDL events. It can also be
executed in response to certain system-defined stored
procedures that do DDL-like operations.
• The DDL triggers are useful in the following scenario:
• When we need to prevent the database schema from
changing
• When we need to audit changes made in the database
schema
• When we need to respond to a change made in the
database schema
DML Triggers
• DML triggers are fired in response to DML events
like INSERT, UPDATE, and DELETE statements in
the user's table or view. It can also be executed
in response to DML-like operations performed by
system-defined stored procedures.
• The DML triggers can be classified into two
types:
• After Triggers
• Instead Of Triggers
After Triggers
• After trigger fires, when SQL Server completes
the triggering action successfully, that fired it.
Generally, this trigger is executed when a table
completes an insert, update or delete operations.
It is not supported in views. Sometimes it is
known as FOR triggers.
Instead of Triggers
• Instead of Trigger fires before SQL Server begins to
execute the triggering operation that triggered it. It means
that no condition constraint check is needed before the
trigger runs. As a result, even if the constraint check fails,
this trigger will fire. It is the opposite of the AFTER trigger.
We can create the INSTEAD OF triggers on a table that
executes successfully but doesn't contain the table's actual
insert, update, or delete operations.
• We can classify this trigger further into three types:
• INSTEAD OF INSERT Trigger
• INSTEAD OF UPDATE Trigger
• INSTEAD OF DELETE Trigger
Logon Triggers
• Logon triggers are fires in response to a LOGON
event. The LOGON event occurs when a user session
is generated with an SQL Server instance, which is
made after the authentication process of logging is
completed but before establishing a user session. As
a result, the SQL Server error log will display all
messages created by the trigger, including error
messages and the PRINT statement messages. If
authentication fails, logon triggers do not execute.
These triggers may be used to audit and control
server sessions, such as tracking login activity or
limiting the number of sessions for a particular login.
Advantages
• The following are the advantages of using triggers in SQL
Server:
• Triggers set database object rules and roll back if any
change does not satisfy those rules. The trigger will
inspect the data and make changes if necessary.
• Triggers help us to validate data before inserted or
updated.
• Triggers help us to keep a log of records.
• Triggers increase SQL queries' performance because they
do not need to compile each time they are executed.
• Triggers reduce the client-side code that saves time and
effort.
• Triggers are easy to maintain.
Disadvantages
• The following are the disadvantages of using triggers in SQL
Server:
• Triggers only allow using extended validations.
• Triggers are invoked automatically, and their execution is
invisible to the user. Therefore, it isn't easy to troubleshoot
what happens in the database layer.
• Triggers may increase the overhead of the database server.
• We can define the same trigger action for multiple user
actions such as INSERT and UPDATE in the same CREATE
TRIGGER statement.
• We can create a trigger in the current database only, but it
can reference objects outside the current database.
DML before triggers
• SET linesize 300;
• DROP Table emp;
• CREATE TABLE emp (
• Id INT PRIMARY KEY,
• Name VARCHAR(15),
• Salary NUMBER(8, 2),
• );
• INSERT INTO emp (Id, Name, Salary) VALUES (1001, 'John', 30000);
• INSERT INTO emp (Id, Name, Salary,) VALUES (1002, 'Smith', 31000);
• INSERT INTO emp (Id, Name, Salary,) VALUES (1003, 'James', 42000);
• INSERT INTO emp (Id, Name, Salary) VALUES (1004, 'John', 43000);
• INSERT INTO emp (Id, Name, Salary,) VALUES (1005, 'Smith', 45000);
• INSERT INTO emp (Id, Name, Salary,) VALUES (1006, 'James', 23000);
• Create trigger salary_difference
• Before insert or delete or update on emp
• For each row
• Declare salary_difference number;
• Begin
• salary_difference := :new.salary – old.salary;
• dbms_output.put_line(‘Old salary: ‘ || :old.salary);
• dbms_output.put_line(‘New salary: ‘ || :new.salary);
• dbms_output.put_line(‘Salary difference: ‘ || :
salary_difference);
• end;
• /
• Sql> insert into emp values(1007, ’rahul’, 34000);
• Sql> delete from emp where id = 1007;
• Sql> update emp set salary = 35000 where
id=1001;
DML after triggers
• SET linesize 300;
• DROP Table Employee;
• CREATE TABLE employee (
• Id INT PRIMARY KEY,
• Name VARCHAR(15),
• Salary NUMBER(8, 2),
• );
• INSERT INTO employee (id, Name, Salary) VALUES (1001, 'John', 30000);
• INSERT INTO employee (id, Name, Salary,) VALUES (1002, 'Smith', 31000);
• INSERT INTO employee (id, Name, Salary,) VALUES (1003, 'James', 42000);
• INSERT INTO employee (id, Name, Salary) VALUES (1004, 'John', 43000);
• INSERT INTO employee (id, Name, Salary,) VALUES (1005, 'Smith', 45000);
• INSERT INTO employee (id, Name, Salary,) VALUES (1006, 'James', 23000);
• SET linesize 300;
• DROP Table Employee;
• CREATE TABLE employeelog (
• Id INT PRIMARY KEY,
• Name VARCHAR(15),
• Salary NUMBER(8, 2),
• );
DML after triggers
• Create trigger employeelogtrigger
• After insert or delete or update on employee
• For each row
• Begin
• If inserting then
• Insert into employeelog values (:new.id, ‘ insert command fired’);
• elsif updating then
• Insert into employeelog values (:new.id, ‘ update command fired’);
• elsif deleting then
• Insert into employeelog values (:new.id, ‘ delete command fired’);
• End if;
• end;
• /
• Update employee set salary = 45000 where Id=1001;
• Select * from employee;
• Select * from employeelog;
• INSERT INTO employee (id, Name, Salary,) VALUES (1007, ‘anaya', 64000);
• Select * from employee;
• Select * from employeelog;
• Delete from employee where id=1007;
• Select * from employee;
• Select * from employeelog;
Instead off triggers
• You can control the default behavior of DML
commands on Views but not on tables.
• Syntax
Create [or replace] Trigger trigger-name
Instead of operation { insert [or] | update [or] |delete [or] |Merge }
On view_name
[for each row]
Begin
Executable-statements
END;
/
• SET linesize 300;
• DROP Table Employee;
• CREATE TABLE employee (
• Id INT,
• Name VARCHAR(15),
• Salary NUMBER(8, 2),
• );
• INSERT INTO employee (id, Name, Salary) VALUES (1001,
'John', 30000);
• INSERT INTO employee (id, Name, Salary) VALUES (1002,
'Smith', 31000);
• INSERT INTO employee (id, Name, Salary) VALUES (1003,
'James', 42000);
• SET linesize 300;
• CREATE TABLE employeelog (
• Id INT,
• Salary NUMBER(8, 2),
• location VARCHAR(15),
• );
• INSERT INTO employee (id, salary, location) VALUES (1004,
‘ali', fsd);
• INSERT INTO employee (id, salary, location) VALUES (1005,
‘saba', lhr);
• CREATE VIEW vw_dragon As
• Select id, name, salary, location FROM employee,
employeelog;
Instead of insert
INSERT INTO vw_dragon values (1006,
ronaldo, 65000, portugal);
• Create trigger tr_insert
• Instead of insert on vw_dragon
• For each row
• Begin
• Insert into employee (id, Name, Salary)
values (:new.id, :new. Name, :new. Salary
);
• Insert into employeelog (id, salary,
location) values (:new.id, :new. Salary,
:new. location );
• end;
• /
• INSERT INTO vw_dragon values (1006, ronaldo, 65000,
portugal);
• Instead of update
• Update vw_dragon set name = messi
where location=‘portugal’;
Create trigger tr_update
Instead of update on vw_dragon
For each row
Begin
update employee set name= :new.name
Where name= :old.name;
update employeelog set location=
:new.location
Where location= :old. location;
end;
/
• Instead of delete
Create trigger tr_delete
Instead of delete on vw_dragon
For each row
Begin
Delete from employee
Where name= :old.name;
Delete from employeelog
Where location= :old. location;
end;
/
Delete from vw_dragon where name=
ali;
System level trigger
• Comes into action when some system event occur e.g. database log on, log off, start up,
or shut down, server error (used for monitoring activities for system events)
• Syntax
Create or replace Trigger trigger-name
before | after database _event on database/schema
Begin
PL/SQL code
END;
/