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
Arun Sial
 
ODP
Introduction to triggers
Command Prompt., Inc
 
PPTX
Triggers
Pooja Dixit
 
PPTX
Using triggers in my sql database
Mbarara University of Science and technology
 
PPT
Oracle Database Trigger
Eryk Budi Pratama
 
PPT
Database Triggers
Aliya Saldanha
 
PDF
Trigger in DBMS
A. S. M. Shafi
 
PPT
Trigger
Slideshare
 
Database object, sub query, Join Commands & Lab Assignment
Arun Sial
 
Introduction to triggers
Command Prompt., Inc
 
Triggers
Pooja Dixit
 
Using triggers in my sql database
Mbarara University of Science and technology
 
Oracle Database Trigger
Eryk Budi Pratama
 
Database Triggers
Aliya Saldanha
 
Trigger in DBMS
A. S. M. Shafi
 
Trigger
Slideshare
 

What's hot (11)

PPTX
Trigger in mysql
Prof.Nilesh Magar
 
PDF
Managing Mocks
Helen Sherwood-Taylor
 
KEY
View triggers pg_east_20110325
David Fetter
 
PDF
The Ring programming language version 1.2 book - Part 16 of 84
Mahmoud Samir Fayed
 
PDF
Sql (Introduction to Structured Query language)
Mohd Tousif
 
PPT
Les13
arnold 7490
 
PPTX
trigger dbms
kuldeep100
 
PPTX
Object Oriented Software Engineering
Ali Haider
 
DOCX
Cara membuat software dj
Moro Aji Pangestu
 
PDF
How to build a debug view almost for free
Vincent Pradeilles
 
DOCX
Coding java.txt
Putera Sumatera
 
Trigger in mysql
Prof.Nilesh Magar
 
Managing Mocks
Helen Sherwood-Taylor
 
View triggers pg_east_20110325
David Fetter
 
The Ring programming language version 1.2 book - Part 16 of 84
Mahmoud Samir Fayed
 
Sql (Introduction to Structured Query language)
Mohd Tousif
 
trigger dbms
kuldeep100
 
Object Oriented Software Engineering
Ali Haider
 
Cara membuat software dj
Moro Aji Pangestu
 
How to build a debug view almost for free
Vincent Pradeilles
 
Coding java.txt
Putera Sumatera
 
Ad

Viewers also liked (20)

PPTX
Sql server ___________session3-normailzation
Ehtisham Ali
 
PPTX
SQL Server 2008 Spatial Data - Getting Started
Integrated Network Strategies
 
PPTX
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
Andrey Gershun
 
PPTX
Alasql.js - SQL сервер на JavaScript
Andrey Gershun
 
PPT
Module08
Sridhar P
 
PPT
Module03
Sridhar P
 
PPTX
Alasql - база данных SQL на JavaScript (MoscowJS)
Andrey Gershun
 
PPT
Module07
Sridhar P
 
PDF
High Performance Front-End Development
drywallbmb
 
PDF
Spatialware_2_Sql08
Mike Osbourn
 
PDF
Multidimensional model programming
Steve Xu
 
PDF
X query language reference
Steve Xu
 
PDF
Multi-thematic spatial databases
Conor Mc Elhinney
 
PPT
Module04
Sridhar P
 
PPT
SQL Server 2008 for Developers
llangit
 
DOC
Css introduction
Sridhar P
 
PPTX
Sql Server Data Tools - Codenamed JUNEAU
Lohith Goudagere Nagaraj
 
PPT
Module01
Sridhar P
 
PPT
Module05
Sridhar P
 
PDF
Transact sql data definition language - ddl- reference
Steve Xu
 
Sql server ___________session3-normailzation
Ehtisham Ali
 
SQL Server 2008 Spatial Data - Getting Started
Integrated Network Strategies
 
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
Andrey Gershun
 
Alasql.js - SQL сервер на JavaScript
Andrey Gershun
 
Module08
Sridhar P
 
Module03
Sridhar P
 
Alasql - база данных SQL на JavaScript (MoscowJS)
Andrey Gershun
 
Module07
Sridhar P
 
High Performance Front-End Development
drywallbmb
 
Spatialware_2_Sql08
Mike Osbourn
 
Multidimensional model programming
Steve Xu
 
X query language reference
Steve Xu
 
Multi-thematic spatial databases
Conor Mc Elhinney
 
Module04
Sridhar P
 
SQL Server 2008 for Developers
llangit
 
Css introduction
Sridhar P
 
Sql Server Data Tools - Codenamed JUNEAU
Lohith Goudagere Nagaraj
 
Module01
Sridhar P
 
Module05
Sridhar P
 
Transact sql data definition language - ddl- reference
Steve Xu
 
Ad

Similar to Module06 (20)

PDF
Triggers in plsql
Arun Sial
 
PPT
Intro to tsql unit 15
Syed Asrarali
 
DOCX
Trigger
Durgaprasad Yadav
 
PPTX
Trigger
VForce Infotech
 
PDF
Triggers in PL introduction yo database s
MrSushilMaurya
 
PPTX
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
PPT
Lecture 4. MS SQL. DML Triggers
Alexey Furmanov
 
PPSX
Sql triggers
Chandan Banerjee
 
PPTX
Lab07_Triggers.pptx
KhngNguyn81
 
DOCX
Final ProjectBe sure to follow the instructions for each step as.docx
voversbyobersby
 
PPTX
triggersandactivedatabasesindatabases.pptx
ManvithaReddy44
 
PPTX
Sql tutorial
prabhu rajendran
 
PPT
TRIGGERS IN DATABASE MANAGEMENT SYSTEM.ppt
NehaJM
 
PPTX
triggers.pptx
Zaid227349
 
PPT
Mca ii-dbms-u-v-transaction management
Rai University
 
PPTX
DOODB_LAB.pptx
FilestreamFilestream
 
PDF
triggeroracle-eryk-130621201822-phpapp01.pdf
saikumar580678
 
PPTX
Exceptions Triggers function in SQL by Vasant Bhabad
vasant Bhabad
 
PPT
Les08 (manipulating data)
Achmad Solichin
 
Triggers in plsql
Arun Sial
 
Intro to tsql unit 15
Syed Asrarali
 
Triggers in PL introduction yo database s
MrSushilMaurya
 
PLSQL.pptxokokokoo9oooodjdjfjfjfjrjejrjrrjrj
KathanPatel49
 
Lecture 4. MS SQL. DML Triggers
Alexey Furmanov
 
Sql triggers
Chandan Banerjee
 
Lab07_Triggers.pptx
KhngNguyn81
 
Final ProjectBe sure to follow the instructions for each step as.docx
voversbyobersby
 
triggersandactivedatabasesindatabases.pptx
ManvithaReddy44
 
Sql tutorial
prabhu rajendran
 
TRIGGERS IN DATABASE MANAGEMENT SYSTEM.ppt
NehaJM
 
triggers.pptx
Zaid227349
 
Mca ii-dbms-u-v-transaction management
Rai University
 
DOODB_LAB.pptx
FilestreamFilestream
 
triggeroracle-eryk-130621201822-phpapp01.pdf
saikumar580678
 
Exceptions Triggers function in SQL by Vasant Bhabad
vasant Bhabad
 
Les08 (manipulating data)
Achmad Solichin
 

Recently uploaded (20)

PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PDF
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PDF
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Virus sequence retrieval from NCBI database
yamunaK13
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 

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, ‘[email protected]', ‘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','[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_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, '[email protected]', '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’