Download - Module06
6.1: Introduction to Triggers
SQL Server 2005
2
Objectives
At the end of this presentation you should be able to:• Understand the concept of Triggers• Understand various types of Triggers• Understand the concept of Magic tables• Create various types of Triggers• Understand the concept of Nested Triggers• Understand the concept of Recursive Triggers• Perform operations on triggers
3
• Introduction to Triggers• Types of Triggers• Magic Tables• Creating Triggers• Nested Triggers• Recursive Triggers• Operations performed on triggers
Contents
4
Introduction to Triggers
• A trigger is an object contained within an SQL server database that is used to execute a batch of SQL code whenever a specific event occurs.
• Triggers allow us to execute a batch of code when either an insert, update or delete command is executed.
• As the name suggests, automatically trigger is fired whenever an insert, update or delete SQL command is executed against a specific table.
5
Introduction to Triggers (Continued)
• Triggers are associated with a single table.• One of the most important use of a trigger is to
enforce referential integrity. • You can create multiple triggers on a table per
each action.• You can specify which trigger fires first or fires
last using sp_settriggerorder stored procedure.
6
Types of Triggers
• Triggers are of the following types:– After triggers: These are executed after the action
of the INSERT,UPDATE, or DELETE statement is performed. These triggers are also known as “FOR” triggers or even simply “triggers”.
– Instead of triggers: These fire instead of the operation that fires the trigger.
7
Magic Tables
• The inserted and deleted tables known as Magic Tables • update () and columns_updated() functions can be used to
determine the changes being caused by DML statements.• The below table explains how the Inserted and Deleted
Tables are used for Insert, Update and Delete Operations
Operation Inserted Table Deleted Table
Insert Will have the inserted row 0 rows.
Delete 0 rows Will have the rows deleted
Update Will have the updated row. Will have the row before updation.
• The update() function helps to identify the column updated.
8
• A trigger can be created using the CREATE TRIGGER statement.
• The syntax is as under:
How To Create Triggers
CREATE TRIGGER TRIGGER_NAME ON TABLE_NAME FOR { INSERT | UPDATE | DELETE [, ..]} AS SQL_STATEMENTS [ RETURN ]
9
Trigger for Insert
• The below trigger gets executed when a new employee is added to the employee table.
create trigger trgInsertEmpon employeefor insertasbegin
declare @dcode char(4)select @dcode = dept_code from inserted
update department set no_of_emp = no_of_emp + 1 where dept_code = @dcode
print 'The Department updated succesfully'end
10
Trigger for Insert (Continued…)
• Suppose we execute the following query:
• insert into employees values ('E003',‘Mary',‘Delhi',33, '(044)-23423434','D002','10-10-2005',150000, ‘[email protected]', ‘F')
ECode EName City Age DeptCode .. ..
E003 Mary Delhi 33 D002 .. ..
Table: inserted
Table : Employee
ECode EName City Age DeptCode .. ..
E001 Raj Bangalore 23 D001 .. ..
E002 Ashok Bangalore 34 D002 .. ..
E003 Mary Delhi 33 D002 .. ..
11
Example - Trigger for Delete
create trigger trgUpdateEmpon Employeefor deleteasbegindeclare @dcode char(4)select @dcode = DeptCode from deletedupdate Department set no_of_emp = no_of_emp - 1 where DeptCode = @dcodeprint 'The Department updated succesfully'end
delete from employee where id= 'E002‘--------------------------------------------------------Output(1 row(s) affected)The Department updated succesfully
12
Trigger for Delete (Continued…)
• Suppose we execute the following query:delete from employee where id= 'E002‘
Id Name Id Name
E001 John
DeptCodeDeptCode
D001
E002 Mike D002
E002 Mike D002
Table: deleted Table: Employee
Record being deleted from employee table and inserted in deleted table
13
Trigger for Update
alter trigger trgUpdateDeptCodeon Employeefor update asbegin if update(DeptCode) begindeclare @olddept char(4), @newdept char(4)
select @olddept = DeptCode from deletedselect @newdept = DeptCode from insertedupdate Department set no_of_emp = no_of_emp - 1 where DeptCode = @olddeptupdate Department set no_of_emp = no_of_emp + 1 where DeptCode = @newdept
print 'The Employee moved successfully' endend
14
Trigger for Update (Continued…)
• Suppose we execute the following query:update employee set DeptCode = 'D003' where ECode = 'E001‘
ECode EName DeptCode .. ..
E001 Raj D003 .. ..
Table: Employee (Before updation) Table: Employee (After updation)
Table: deleted Table: inserted
ECode EName DeptCode .. ..
E001 Raj D001 .. ..
ECode EName DeptCode .. ..
E001 Raj D001 .. ..
ECode EName DeptCode .. ..
E001 Raj D003 .. ..
15
Instead of Triggers• Only the ‘Instead of’ trigger will get fired instead of the operation that
fires the trigger. Example:
Create Trigger trgInsteadInsertOn User_DetailsINSTEAD OF INSERTASBEGIN
Print ('INSTEAD OF Trigger [trgInsteadInsert] – Trigger executed !!')END-------------------------------------------------INSERT INTO USER_DETAILS(USERID, FNAME,LNAME, MNAME, EMAIL)VALUES(100, 'FName','LName','MName','[email protected]')
INSTEAD OF Trigger [trgInsteadInsert] – Trigger executed !!(1 row(s) affected)
Output
16
Nested Triggers
• Nested Triggers are triggers that fire due to action of other triggers.
• To check whether nested triggers are allowed on your server, execute the following stored procedure:exec sp_configure ‘nested triggers’
• If run-value is 0, your server is not allowing nested triggers.
• If run-value is 1, your server is allowing nested triggers.
17
Recursive Triggers
• When a Trigger is eventually going to call itself. There are two types of recursive triggers:
– Direct Recursion: A direct recursion is the one that performs the same operation on the same table causing the trigger to fire itself again.
– Indirect Recursion: An indirect recursion is the one that fires a trigger on another table and eventually the nested trigger ends up firing the first trigger again.
18
To Get information about triggers
• In order to get information about triggers on a particular table, you can use the following stored procedure:
exec sp_helptrigger TABLE_NAME
The above command will list the names of triggers along with their types which you have created on a particular table.
19
Operations on Trigger
To Alter a trigger: • Following statement is used to alter a trigger:
alter trigger trigger_nameon table_namefor { INSERT | UPDATE | DELETE [, ..]}AsSQL_STATEMENTS
To Drop a trigger: • Following statement is used to drop a trigger:
drop trigger trigger_name
20
Operations on Trigger (continued…..)
To View the definition of a trigger: • Use sp_helptext stored procedure to view a
trigger’s definition in the following manner:
exec sp_helptext trigger_name
• Trigger’s definition comprises of the statements which we used at the time of creation of that trigger.
21
Key points
• Triggers allow us to execute a batch of SQL code when either an insert,update or delete command is executed.
• There are mainly two types of triggers: After and Instead of triggers.
• The inserted and deleted tables are popularly known as Magic tables
• You can create a trigger using CREATE TRIGGER statement.
• Nested Triggers are triggers that fire due to action of other triggers.
22
Key points (Continued)
• Recursive triggers are of two types: Direct and Indirect recursion.
• You can alter a trigger using alter trigger trigger_name statement.
• You can drop a trigger using drop trigger trigger_name statement.
• You can view the definition of a trigger using sp_helptext stored procedure
23
Activity Time (45 minutes)
• Activity: 6.1
Create a trigger to update the NoOfEmployees when an Employee is added to the Employee table.
• Activity: 6.2
Create a trigger to restrict the user from deleting the department from the Department table. And print a message that the record cannot be deleted.
• Activity: 6.3
Create a trigger to restrict the user to update the salary value in the Employee table.
24
Questions & Comments