SlideShare a Scribd company logo
6.1: Introduction to Triggers   SQL Server 2005
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
Introduction to Triggers Types of Triggers Magic Tables Creating Triggers Nested Triggers Recursive Triggers Operations performed on triggers Contents
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.
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.
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.
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 The update() function helps to identify the column updated.   Will have the row before updation. Will have the updated row. Update Will have the rows deleted 0 rows Delete 0 rows. Will have the inserted row Insert Deleted Table Inserted Table Operation
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 ]
Trigger for Insert The below trigger gets executed when a new employee is added to the employee table. create trigger trgInsertEmp on employee for insert as begin 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
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, ‘Mary@abc.com', ‘F') Table: inserted  Table : Employee  .. .. .. D002 33 Delhi Mary E003 .. DeptCode Age  City  EName  ECode .. .. .. D002 33 Delhi Mary E003 .. .. D002 34 Bangalore Ashok E002 .. .. D001 23 Bangalore Raj E001 .. DeptCode Age  City  EName  ECode
Example - Trigger for Delete create trigger t rgUpdateEmp on  E mployee for delete as begin declare @dcode char(4) select @dcode =  D ept C ode from deleted update  D epartment set no _ of_emp = no_of_emp - 1 where  D ept C ode =  @ dcode print 'The Department updated succesfully' end delete from employee where id= 'E002‘ -------------------------------------------------------- Output (1 row(s) affected) The Department updated succesfully
Trigger for Delete (Continued…) Suppose we execute the following query: delete from employee where id= 'E002‘ Id Name Id Name E001 John DeptCode DeptCode D001 Table: deleted Table: Employee Record being deleted from employee table and inserted in deleted table E002 Mike D002 E002 Mike D002
Trigger for Update alter trigger trgUpdateDeptCode on Employee for update as begin if update(DeptCode) begin declare @olddept char(4), @newdept char(4) select @olddept = DeptCode from deleted select @newdept = DeptCode from inserted update Department set no_of_emp = no_of_emp - 1 where DeptCode = @olddept update Department set no_of_emp = no_of_emp + 1 where DeptCode = @newdept print 'The Employee moved successfully' end end
Trigger for Update (Continued…) Suppose we execute the following query: update employee set DeptCode = 'D003' where ECode = 'E001‘ Table: Employee (Before updation) Table: Employee (After updation) Table: deleted Table: inserted .. .. .. D003 Raj E001 .. DeptCode EName  ECode .. .. .. D001 Raj E001 .. DeptCode EName  ECode .. .. .. D001 Raj E001 .. DeptCode EName  ECode .. .. .. D003 Raj E001 .. DeptCode EName  ECode
Instead of Triggers Only the ‘Instead of’ trigger will get fired instead of the operation that fires the trigger.  Example: Create Trigger trgInsteadInsert On User_Details INSTEAD OF INSERT AS BEGIN Print ('INSTEAD OF Trigger [trgInsteadInsert] – Trigger executed !!') END ------------------------------------------------- INSERT INTO USER_DETAILS(USERID, FNAME,LNAME, MNAME, EMAIL) VALUES(100, 'FName','LName','MName','test@test.com') INSTEAD OF Trigger [trgInsteadInsert] – Trigger executed !! (1 row(s) affected) Output
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.
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.
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.
Operations on Trigger To Alter a trigger:  Following statement is used to alter a trigger: alter trigger  trigger_name on table_name for  { INSERT | UPDATE | DELETE [, ..]} As SQL_STATEMENTS To Drop a trigger:   Following statement is used to drop a trigger: drop trigger  trigger_name
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.
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.
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
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.
Questions & Comments

More Related Content

DOCX
Database object, sub query, Join Commands & Lab Assignment
ODP
Introduction to triggers
PPTX
Triggers
PPTX
Using triggers in my sql database
PPT
Oracle Database Trigger
PPT
Database Triggers
PDF
Trigger in DBMS
PPT
Trigger
Database object, sub query, Join Commands & Lab Assignment
Introduction to triggers
Triggers
Using triggers in my sql database
Oracle Database Trigger
Database Triggers
Trigger in DBMS
Trigger

What's hot (11)

PPTX
Trigger in mysql
PDF
Managing Mocks
KEY
View triggers pg_east_20110325
PDF
The Ring programming language version 1.2 book - Part 16 of 84
PDF
Sql (Introduction to Structured Query language)
PPT
PPTX
trigger dbms
PPTX
Object Oriented Software Engineering
DOCX
Cara membuat software dj
PDF
How to build a debug view almost for free
DOCX
Coding java.txt
Trigger in mysql
Managing Mocks
View triggers pg_east_20110325
The Ring programming language version 1.2 book - Part 16 of 84
Sql (Introduction to Structured Query language)
trigger dbms
Object Oriented Software Engineering
Cara membuat software dj
How to build a debug view almost for free
Coding java.txt
Ad

Viewers also liked (20)

PPTX
Sql server ___________session3-normailzation
PPTX
SQL Server 2008 Spatial Data - Getting Started
PPTX
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
PPTX
Alasql.js - SQL сервер на JavaScript
PPT
Module08
PPT
Module03
PPTX
Alasql - база данных SQL на JavaScript (MoscowJS)
PPT
Module07
PDF
High Performance Front-End Development
PDF
Spatialware_2_Sql08
PDF
Multidimensional model programming
PDF
X query language reference
PDF
Multi-thematic spatial databases
PPT
Module04
PPT
SQL Server 2008 for Developers
DOC
Css introduction
PPTX
Sql Server Data Tools - Codenamed JUNEAU
PPT
Module01
PPT
Module05
PDF
Transact sql data definition language - ddl- reference
Sql server ___________session3-normailzation
SQL Server 2008 Spatial Data - Getting Started
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
Alasql.js - SQL сервер на JavaScript
Module08
Module03
Alasql - база данных SQL на JavaScript (MoscowJS)
Module07
High Performance Front-End Development
Spatialware_2_Sql08
Multidimensional model programming
X query language reference
Multi-thematic spatial databases
Module04
SQL Server 2008 for Developers
Css introduction
Sql Server Data Tools - Codenamed JUNEAU
Module01
Module05
Transact sql data definition language - ddl- reference
Ad

Similar to Module06 (20)

PPTX
PPTX
triggers.pptx
PDF
Triggers in PL introduction yo database s
PPT
Intro to tsql unit 15
PPT
Lecture 4. MS SQL. DML Triggers
PDF
Lecture Notes Unit5 chapter16 Trigger Creation
PDF
Triggers (1).pdf
PPT
10 Creating Triggers
PPTX
6. triggers
PDF
Triggers and active database
PPT
Mca ii-dbms-u-v-transaction management
PPTX
triggersandactivedatabasesindatabases.pptx
PPTX
Sql server ___________session_19(triggers)
PPTX
Lab07_Triggers.pptx
PDF
triggeroracle-eryk-130621201822-phpapp01.pdf
PPTX
Triggers.PPTX
PPT
TRIGGERS IN DATABASE MANAGEMENT SYSTEM.ppt
PPTX
11 - Trigger mysql advance materi for student.pptx
triggers.pptx
Triggers in PL introduction yo database s
Intro to tsql unit 15
Lecture 4. MS SQL. DML Triggers
Lecture Notes Unit5 chapter16 Trigger Creation
Triggers (1).pdf
10 Creating Triggers
6. triggers
Triggers and active database
Mca ii-dbms-u-v-transaction management
triggersandactivedatabasesindatabases.pptx
Sql server ___________session_19(triggers)
Lab07_Triggers.pptx
triggeroracle-eryk-130621201822-phpapp01.pdf
Triggers.PPTX
TRIGGERS IN DATABASE MANAGEMENT SYSTEM.ppt
11 - Trigger mysql advance materi for student.pptx

Recently uploaded (20)

PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Pharma ospi slides which help in ospi learning
PDF
Complications of Minimal Access Surgery at WLH
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
RMMM.pdf make it easy to upload and study
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
master seminar digital applications in india
PPTX
Institutional Correction lecture only . . .
Final Presentation General Medicine 03-08-2024.pptx
TR - Agricultural Crops Production NC III.pdf
Insiders guide to clinical Medicine.pdf
VCE English Exam - Section C Student Revision Booklet
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Anesthesia in Laparoscopic Surgery in India
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
O7-L3 Supply Chain Operations - ICLT Program
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Cell Types and Its function , kingdom of life
Basic Mud Logging Guide for educational purpose
Pharma ospi slides which help in ospi learning
Complications of Minimal Access Surgery at WLH
Microbial disease of the cardiovascular and lymphatic systems
O5-L3 Freight Transport Ops (International) V1.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
RMMM.pdf make it easy to upload and study
Module 4: Burden of Disease Tutorial Slides S2 2025
master seminar digital applications in india
Institutional Correction lecture only . . .

Module06

  • 1. 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 The update() function helps to identify the column updated. Will have the row before updation. Will have the updated row. Update Will have the rows deleted 0 rows Delete 0 rows. Will have the inserted row Insert Deleted Table Inserted Table Operation
  • 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 trgInsertEmp on employee for insert as begin 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, ‘Mary@abc.com', ‘F') Table: inserted Table : Employee .. .. .. D002 33 Delhi Mary E003 .. DeptCode Age City EName ECode .. .. .. D002 33 Delhi Mary E003 .. .. D002 34 Bangalore Ashok E002 .. .. D001 23 Bangalore Raj E001 .. DeptCode Age City EName ECode
  • 11. Example - Trigger for Delete create trigger t rgUpdateEmp on E mployee for delete as begin declare @dcode char(4) select @dcode = D ept C ode from deleted update D epartment set no _ of_emp = no_of_emp - 1 where D ept C ode = @ dcode print '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 DeptCode DeptCode D001 Table: deleted Table: Employee Record being deleted from employee table and inserted in deleted table E002 Mike D002 E002 Mike D002
  • 13. Trigger for Update alter trigger trgUpdateDeptCode on Employee for update as begin if update(DeptCode) begin declare @olddept char(4), @newdept char(4) select @olddept = DeptCode from deleted select @newdept = DeptCode from inserted update Department set no_of_emp = no_of_emp - 1 where DeptCode = @olddept update Department set no_of_emp = no_of_emp + 1 where DeptCode = @newdept print 'The Employee moved successfully' end end
  • 14. Trigger for Update (Continued…) Suppose we execute the following query: update employee set DeptCode = 'D003' where ECode = 'E001‘ Table: Employee (Before updation) Table: Employee (After updation) Table: deleted Table: inserted .. .. .. D003 Raj E001 .. DeptCode EName ECode .. .. .. D001 Raj E001 .. DeptCode EName ECode .. .. .. D001 Raj E001 .. DeptCode EName ECode .. .. .. D003 Raj E001 .. DeptCode EName ECode
  • 15. Instead of Triggers Only the ‘Instead of’ trigger will get fired instead of the operation that fires the trigger. Example: Create Trigger trgInsteadInsert On User_Details INSTEAD OF INSERT AS BEGIN Print ('INSTEAD OF Trigger [trgInsteadInsert] – Trigger executed !!') END ------------------------------------------------- INSERT INTO USER_DETAILS(USERID, FNAME,LNAME, MNAME, EMAIL) VALUES(100, 'FName','LName','MName','test@test.com') 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_name on table_name for { INSERT | UPDATE | DELETE [, ..]} As SQL_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.

Editor's Notes

  • #5: Faculty notes You need to provide each trigger with a name and define it for a particular table or view in a database. You also have an option of encrypting the trigger so that no one (not even the owner) can look at the original code. Triggers can be used to enforce referential integrity: You could create a trigger that, upon the insertion of a record looks for the corresponding value of the foreign key in the parent table. If the value isn’t found, the transaction can be rolled back. Difference between triggers and declarative constraints A declarative integrity constraint applies to the data which is existing in the table and any statement that manipulates the table. A trigger does not apply to the data which was there in the table before the trigger was created. The triggers are used to implement more complex data integrity. The Triggers except InsteadOfTriggers are Reactive. But the declarative constraints are Proactive. When the table is manipulated by using Insert, Update and Delete statements, first the table is updated and the trigger gets executed. But the declarative constraints are checked first and the table is manipulated.
  • #6: Faculty Notes: Setting the triggering order: In SQL Server 7.0, triggers were understood to be fired in no particular order. Since SQL Server 2000, a new stored procedure has been added called sp_settriggerorder.   The purpose of sp_settriggerorder is to set for a particular operation (INSERT, UPDATE, or DELETE) for a particular table which trigger will fire first and/or which trigger will fire last.  Any and all triggers not specified as first or last will fire in no particular order.  Our stored procedure has the following syntax: EXEC sp_settriggerorder <trigger name> , <order> , ' <operation> ‘ For instance: EXEC sp_settriggerorder trig_insert_Employee, first, 'INSERT‘ or EXEC sp_settriggerorder @triggername=‘myTrigger’, @order = ‘first’ We have three choices on order: first, last, and none.  We can use none to toggle a trigger to no longer fire first or last. 
  • #7: Faculty Notes: After you have specified which table or view is to be the beneficiary of the trigger, you need to define the trigger as an AFTER or INSTEAD OF trigger. You cannot define an AFTER trigger for a view.
  • #10: Faculty notes Explanation of the above example : When a new employee is added to the employee table, the no_of_emp column value in the department table for a particular department to which the employee is added, will be incremented by one. For the above example to execute, run the following script. Create the following 2 tables, Employee Table: Create table employee ( emp_code char(4), emp_name varchar(15), city varchar(15), age int, phone char(14), dept_code char(4), doj datetime, salary money, email varchar(20) ) Department table: Create table department ( dept_code char(4), dept_name varchar(15), no_of_emp int ) Execute the below statement to see whether the trigger executes. insert into employee values ('E002','Raghu','Bangalore',45, '(044)-23423434','D002','10-10-2005',150000, 'raghu@abc.com', 'M') Result : check to see if the no_of_emp value of the department ‘D002’ in the department table is incremented by one.
  • #11: Faculty notes When the above query is executed, The row is inserted into the employee table and the same row is inserted into the inserted table. As there are many rows in the employee table, we can get access to the row that is just inserted based on the row in the inserted table. And this row in the inserted table is available only during the execution of the trigger.
  • #12: Faculty notes Use the scripts that are mentioned in the previous slide before you create the trigger mentioned in the above slide. Result : When the above delete statement is executed, check to see whether the value of the no_of_emp column is decremented by 1. for the department of the Employee ‘E002’.
  • #13: Faculty notes We have executed the following query: delete from employee where id=‘E002’ When we delete a record from employee table, the deleted record would be put in the deleted table as shown in the above figure. The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and moved to the deleted table. The deleted table and the trigger table have no rows in common. In the above figure, employee is acting as a trigger table.
  • #14: Faculty notes When, the below sql Statement is executed, update employee set dept_code = 'D003' where emp_code = 'E001‘ Assuming that the department code of employee ‘E001’ is ‘D001’, when the above update statement is executed, the no_of_emp of the dept_code column for D001 and D003 departments in the department table are decremented and incremented by 1 respectively. Also, initially it checks to see whether the dept_code is getting updated using the statement update(dept_code), by doing so the trigger body gets executed only if the dept_code is updated.
  • #15: Faculty notes Updation is deletion followed by insertion. In the above example, the record is deleted first from the Employee and put into the deleted table, then the record is updated and inserted into to the Employee Table. After inserting the updated record into the Employee table, the record is inserted into the Inserted Table.
  • #17: Faculty notes To turn off nested triggers, use: Exec sp_configure ‘nested triggers’,0 reconfigure To turn on nested triggers, use: Exec sp_configure ‘nested triggers’,1,reconfigure
  • #18: Faculty notes Example of Indirect recursion: An update on table A fires a trigger which causes an update on table B. The update on table B fires a trigger which does an update on table C. Table C has a trigger which causes an update on table A again. Table A’s trigger fires again. Recursive triggers create a lot of problems. As a result, recursive triggers are turned off by default. If you want to check the status of recursive triggers in a particular database, use: Exec sp_dboption ‘<name of database>’,’recursive triggers’ To turn on recursive triggers, use: Exec db_option ‘<name of database>’, ’recursive triggers’, ’true’ To turn off recursive triggers, use: Exec db_option ‘<name of database>’,’recursive triggers’, ‘false’