0% found this document useful (0 votes)
52 views12 pages

Understanding SQL Triggers Explained

A trigger in SQL is a stored procedure that automatically executes in response to specific events such as INSERT, UPDATE, or DELETE on a table. Triggers are used for maintaining data integrity, cascading changes, and defining custom error messages, and can be classified into DML, DDL, and Logon triggers. DML triggers can be further categorized into After and Instead Of triggers, which handle data modifications and can enforce business rules or log actions in audit tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views12 pages

Understanding SQL Triggers Explained

A trigger in SQL is a stored procedure that automatically executes in response to specific events such as INSERT, UPDATE, or DELETE on a table. Triggers are used for maintaining data integrity, cascading changes, and defining custom error messages, and can be classified into DML, DDL, and Logon triggers. DML triggers can be further categorized into After and Instead Of triggers, which handle data modifications and can enforce business rules or log actions in audit tables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What Is A Trigger In SQL ?

 A trigger is a special kind of stored procedure that automatically executes when an event
occurs in the database server.
 A trigger is a stored procedure that is executed when an attempt is made to modify data in
a table protected by the trigger.
 A trigger cannot be executed directly, nor do they pass or receive parameters.
 A trigger is defined on specific tables and these tables are referred to as trigger tables.
 A trigger is defined on the INSERT, UPDATE, or DELETE action on a table, it fires
automatically when these actions are attempted.
 A trigger is created using the CREATE TRIGGER statement.

Uses Of Triggers
Triggers can contain complex processing logic and are generally used for maintaining low-
level data integrity. Primary uses of triggers can be classified as follows:

 Cascading changes through related tables


o Users can use a trigger to cascade changes through related tables.
 Enforcing complex data integrity than CHECK constraints.
o Unlike CHECK constraints, triggers can reference the columns in other tables
o Can be used to apply complex data integrity checks by,
 Checking constraints before cascading updates or deletes
 Creating multi-row triggers for actions executed on multiple rows
 Enforcing referential integrity between databases
 Defining custom error messages
o Are used for providing more suitable or detailed explanations in certain error
situations.

Types Of Triggers
A trigger can be set to automatically execute an action when a language event occurs in a table or
a view. Triggers in SQL Server 2012 can be classified into three basic types:

 DML Triggers
o Execute when data is inserted, modified, or deleted in a table or a view using the
INSERT, UPDATE, or DELETE statements
 DDL Triggers
o Execute when a table or a view is created, modified, or deleted using the
CREATE, ALTER, or DROP statements.
 Logon Triggers
o Execute stored procedures when a session is established with a LOGON event.

DDL Triggers VS DML Triggers


DDL and DML triggers have different uses and are executed with different database events.

DDL Triggers DML Triggers


DDL Triggers execute stored procedures on DML Triggers execute on INSERT, UPDATE &
CREATE, ALTER & DROP statements. DELETE statements.
DDL Triggers are used to check and control DML triggers are used to enforce business rules
database operations. when data is modified in tables or views.
DDL triggers operate only after the table or a DML triggers execute either while modifying the
view is modified. data or after the data is modified.
DDL triggers are defined at either the database
DML triggers are defined at the database level.
level or the server level.

DML Triggers In SQL


 DML triggers are executed when DML events occur in tables or views. These DML
events include the INSERT, UPDATE, and DELETE statements.
 DML triggers can execute either on completion of the DML events or in place of the
DML events.
 DML triggers enforce referential integrity by cascading changes to related tables when a
row is modified.
 DML triggers can perform multiple actions for each modification statement.
 DML triggers are of three main types namely, INSERT trigger, UPDATE trigger, and
DELETE trigger.

Inserted & Deleted Tables With Triggers In SQL


 Inserted Table
o Contains copies of records that are modified with the INSERT and UPDATE
operations on the trigger table.
o The INSERT and UPDATE operations insert new records into the Inserted and
Trigger table.
 Deleted Table
o Contains copies of records that are modified with the DELETE and UPDATE
operations on the trigger table.
o These operations delete the records from the trigger table and insert them in the
Deleted table.

The Inserted and Deleted tables do not physically remain present in the database and are created
and dropped whenever any triggering events occur.

 Dml Triggers Are Fired Automatically In Response To Dml Events (Insert, Update And
Delete)

DML Triggers Can Be Of 2 Types


1. After Triggers (Also Called For Triggers)
2. Instead Of Triggers
1. Instead Of Insert Trigger
2. Instead Of Update Trigger
3. Instead Of Delete Trigger

After Triggers
 After trigger is executed on completion of INSERT, UPDATE, or DELETE operations
and can be created only on tables.
 A table can have multiple AFTER triggers defined for each INSERT, UPDATE, and
DELETE operation and the user must define the order of execution of triggers.
 After trigger is executed when the constraint check in the table is completed and also the
trigger is executed after the Inserted and Deleted tables are created.

SQL Query For DML After Triggers


-- CREATING STUDENT TABLE
create table tbl_Student
(
Id int primary key identity,
Name varchar(50),
Gender varchar(50),
Class int,
fees int
);
select * from tbl_Student;

-- INSERTING ROWS INTO STUDENT TABLE


insert into tbl_Student values('Osama','Male',10,4000);
insert into tbl_Student values('Anum','Female',9,3500);
insert into tbl_Student values('Talha','Male',8,3000);
insert into tbl_Student values('Maheen','Female',10,4000);
insert into tbl_Student values('Abdul','Male',9,3500);
insert into tbl_Student values('Mushtaq','Male',5,3000);
insert into tbl_Student values('Anas','Male',7,3000);
insert into tbl_Student values('Muneer','Male',8,4000);
insert into tbl_Student values('Momina','Female',9,3000);
insert into tbl_Student values('Aslam','Male',7,4000);
insert into tbl_Student values('Mumtaz','Female',6,3000);

-- CREATING STUDENT'S AUDIT TABLE


create table tbl_Student_Audit
(
Audit_Id int primary key identity,
Audit_Info varchar(max)
);

select * from tbl_Student_Audit;


select * from tbl_Student;

-- CREATING AFTER INSERT TRIGGER


create trigger tr_Student_forinsert
on tbl_Student
after insert
as
begin
select * from inserted
end

-- CREATING AFTER DELETE TRIGGER


create trigger tr_Student_forDelete
on tbl_Student
after delete
as
begin
select * from deleted
end

-- CREATING AFTER UPDATE TRIGGER


create trigger tr_Student_forUpdate
on tbl_Student
after update
as
begin
select * from inserted
select * from deleted
end

update tbl_student set Name = 'Ali', Gender = 'Male'


where id = 12;

delete from tbl_Student where id = 9;


delete from tbl_Student where id = 10;
delete from tbl_Student where id = 13;

-- VIEWING THE SQL QUERY OF TRIGGER


sp_helptext tr_Student_audit_forinsert;

-- CREATING THE AFTER INSERT TRIGGER AND SEND TO DATA TO AUDIT TABLE
-- AFTER INSERT EVENT OCCURS

create trigger tr_Student_audit_forinsert


on tbl_Student
after insert
as
begin
Declare @id int
Select @id = id from inserted
insert into tbl_Student_Audit
values('Student with id ' + Cast(@id as varchar(50)) + ' is added at ' +
Cast(GETDATE() as varchar(50)));
end

-- CREATING THE AFTER DELETE TRIGGER AND SEND TO DATA TO AUDIT TABLE
-- AFTER DELETE EVENT OCCURS

create trigger tr_Student_audit_forDelete


on tbl_Student
after delete
as
begin
Declare @id int
Select @id = id from deleted
insert into tbl_Student_Audit
values('Existing Student with id ' + Cast(@id as varchar(50)) + ' is deleted
at ' + Cast(GETDATE() as varchar(50)));
end

INSTEAD OF Triggers
 Instead Of Triggers Is Executed In Place Of The Insert, Update Or Delete Operations.
 INSTEAD OF Trigger is executed in place of the INSERT, UPDATE, or DELETE
operations.
 Can be created on tables as well as views and there can be only one INSTEAD OF trigger
defined for each INSERT, UPDATE, and DELETE operation.
 INSTEAD OF Triggers are executed before constraint checks are performed on the table
and after the creation of the Inserted and Deleted tables
SQL Query For DML Instead Of Triggers
create table Tbl_Customer
(
Id int primary key,
Name varchar(50),
Gender varchar(20),
City varchar(30),
ContactNo varchar(50)
);

select * from Tbl_Customer;

insert into Tbl_Customer values(1,'Ali','Male','Hyderabad','03335465678');


insert into Tbl_Customer values(2,'Anum','Female','Karachi','03225465678');
insert into Tbl_Customer values(3,'Osama','Male','Sukkur','03135468778');
insert into Tbl_Customer values(4,'Amna','Female','Hyderabad','03005465678');
insert into Tbl_Customer values(5,'Affan','Male','Karachi','03135465678');
insert into Tbl_Customer values(6,'Anas','Male','Hyderabad','03135468774');
insert into Tbl_Customer values(7,'Usman','Male','Karachi','03335468774');

-- CREATING AUDIT TABLE FOR CUSTOMER


create table Customer_Audit_table
(
Audit_Id int primary key identity,
Audit_Information varchar(max)
);
select * from Customer_Audit_table;

-- CREATING INSTEAD OF INSERT TRIGGER WHICH PREVENTS THE INSERTION


create trigger tr_Customer_InsteadOf_Insert
on Tbl_Customer
instead of insert
as
begin
print 'You are not allowed to insert data in this table !!'
end

drop trigger tr_Customer_InsteadOf_Insert;

-- CREATING INSTEAD OF INSERT TRIGGER WHICH INSERTS THE DATA IN AUDIT TABLE

create trigger tr_Customer_InsteadOf_Insert_Audit


on Tbl_Customer
instead of insert
as
begin
insert into Customer_Audit_table values('SomeOne tries to insert data
in customer table at: ' + cast(getdate() as varchar(50)));
end

-- CREATING INSTEAD OF UPDATE TRIGGER WHICH PREVENTS THE UPDATION


create trigger tr_Customer_InsteadOf_Update
on Tbl_Customer
instead of update
as
begin
print 'You are not allowed to update data in this table !!'
end

drop trigger tr_Customer_InsteadOf_Update;

-- CREATING INSTEAD OF UPDATE TRIGGER WHICH INSERTS THE A ROW IN AUDIT TABLE
WHEN SOMEONE TRIES TO UPDATE DATA

create trigger tr_Customer_InsteadOf_Update_Audit


on Tbl_Customer
instead of update
as
begin
insert into Customer_Audit_table values('SomeOne tries to update data
in customer table at: ' + cast(getdate() as varchar(50)));
end

update Tbl_Customer set Name = 'Asif' where id = 6;

-- CREATING INSTEAD OF DELETE TRIGGER WHICH PREVENTS THE DELETION


create trigger tr_Customer_InsteadOf_Delete
on Tbl_Customer
instead of delete
as
begin
print 'You are not allowed to delete anything in this table !!'
end

drop trigger tr_Customer_InsteadOf_Delete;

-- CREATING INSTEAD OF DELETE TRIGGER WHICH INSERTS A ROW IN AUDIT TABLE WHEN
SOMEONE TRIES TO DELETE DATA FROM CUSTOMER TABLE

alter trigger tr_Customer_InsteadOf_Delete_Audit


on Tbl_Customer
instead of delete
as
begin
insert into Customer_Audit_table values('SomeOne tries to delete data
from customer table at: ' + cast(getdate() as varchar(50)));
end

delete from Tbl_Customer where id = 6;

-- VIEWING THE TRIGGER


sp_helptext tr_Customer_InsteadOf_Delete_Audit;

Using Instead Of Triggers With Views


 Can be specified on tables as well as views and provides a wider range and types of
updates that the user can perform against a view.
 We are creating a view called "EMPLOYEE DETAILS VIEW" from 2 parent tables
known as "EMPLOYEE PERSONAL DETAILS" and "EMPLOYEE SALARY
DETAILS".
 When we create a view from a single parent table then we can insert, update or delete in a
view and it successfully reflects in a parent table.
 But When we insert, update or delete data from a view and that view created with the
help of 2 parent tables then SQL engine throws an error that we cannot update in more
than 1 base or parent tables.
 But By Using Instead Of Triggers With Views we can do that.

SQL Query For Using Instead Of Delete Trigger With Views


-- In this example when we tried to delete the data from the view then
-- that data also deletes from the 2 parent tables.

create table Employee_Personal_Details


(
EmpID int,
FirstName varchar(50),
LastName varchar(50),
[Address] varchar(100)
);

insert into Employee_Personal_Details values(1,'Ali','Khan','Latifabad No:8');


insert into Employee_Personal_Details values(2,'Anas','Farhan','Latifabad
No:6');
insert into Employee_Personal_Details values(3,'Zain','Fareed','Latifabad
No:7');
insert into Employee_Personal_Details values(4,'Noman','Khan','Latifabad
No:2');

create table Employee_Salary_Details


(
EmpID int,
Designation varchar(50),
Salary int
);

select * from Employee_Salary_Details;

insert into Employee_Salary_Details values(1,'Accountant',35000);


insert into Employee_Salary_Details values(2,'Manager',45000);
insert into Employee_Salary_Details values(3,'Admin',50000);
insert into Employee_Salary_Details values(4,'Incharge',25000);

select * from Employee_Personal_Details;


select * from Employee_Salary_Details;

create view vW_Employees


as
select [Link], [Link], [Link], [Link], [Link]
from Employee_Personal_Details as A
inner join Employee_Salary_Details as B
on [Link] = [Link];

select * from vW_Employees;

delete from vW_Employees where EmpID = 4;

create trigger tr_Employee_Salary_Delete


on vW_Employees
instead of delete
as
begin
delete from Employee_Personal_Details where EmpID in
(select EmpID from deleted)
delete from Employee_Salary_Details where EmpID in
(select EmpID from deleted)

end

Setting Execution Order of DML Triggers


 SQL Server allows users to specify which AFTER trigger is to be executed first and
which is to be executed last.
 For this purpose, we are going to use System Stored Procedure namely
SP_SETTRIGGERORDER
SP_SETTRIGGERORDER
 1st Parameter: @triggername: is the name of the DML or DDL trigger and the schema to
which it belongs and whose order needs to be specified.
 2nd Parameter: @order: specifies the execution order of the trigger as FIRST, LAST, or
NONE. If FIRST is specified, then the trigger is fired first.
 3rd Parameter: @stmttype (statement_type): specifies the type of SQL statement
(INSERT, UPDATE, or DELETE) that invokes the DML trigger.

Following code snippet executes the Employee_Deletion trigger defined on the table when
the DELETE operation is performed:

EXEC sp_settriggerorder
@triggername = 'Employee_Deletion ',
@order = 'FIRST',
@stmttype = 'DELETE’;

You might also like