SlideShare a Scribd company logo
1 of 24
Download to read offline
6.1: Introduction to Triggers   SQL Server 2005
Objectives ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Contents
Introduction to Triggers ,[object Object],[object Object],[object Object]
Introduction to Triggers (Continued) ,[object Object],[object Object],[object Object],[object Object]
Types of Triggers ,[object Object],[object Object],[object Object]
Magic Tables ,[object Object],[object Object],[object Object],[object Object],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
[object Object],[object Object],How To Create Triggers CREATE TRIGGER  TRIGGER_NAME   ON  TABLE_NAME   FOR { INSERT | UPDATE | DELETE [, ..]}   AS   SQL_STATEMENTS  [ RETURN ]
Trigger for Insert ,[object Object],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…) ,[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],delete from employee where id= 'E002‘ -------------------------------------------------------- Output (1 row(s) affected) The Department updated succesfully
Trigger for Delete (Continued…) ,[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Trigger for Update (Continued…) ,[object Object],[object Object],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 ,[object Object],[object Object],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 ,[object Object],[object Object],[object Object],[object Object],[object Object]
Recursive Triggers ,[object Object],[object Object],[object Object]
To Get information about triggers ,[object Object],[object Object],[object Object]
Operations on Trigger ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Operations on Trigger (continued…..) ,[object Object],[object Object],[object Object],[object Object]
Key points ,[object Object],[object Object],[object Object],[object Object],[object Object]
Key points (Continued) ,[object Object],[object Object],[object Object],[object Object]
Activity Time (45 minutes) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Questions & Comments

More Related Content

What's hot

View triggers pg_east_20110325
View triggers pg_east_20110325View triggers pg_east_20110325
View triggers pg_east_20110325David Fetter
 
The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84Mahmoud Samir Fayed
 
Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Mohd Tousif
 
Object Oriented Software Engineering
Object Oriented Software EngineeringObject Oriented Software Engineering
Object Oriented Software EngineeringAli Haider
 
How to build a debug view almost for free
How to build a debug view almost for freeHow to build a debug view almost for free
How to build a debug view almost for freeVincent Pradeilles
 

What's hot (11)

Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
Managing Mocks
Managing MocksManaging Mocks
Managing Mocks
 
View triggers pg_east_20110325
View triggers pg_east_20110325View triggers pg_east_20110325
View triggers pg_east_20110325
 
The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84
 
Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)
 
Les13
Les13Les13
Les13
 
trigger dbms
trigger dbmstrigger dbms
trigger dbms
 
Object Oriented Software Engineering
Object Oriented Software EngineeringObject Oriented Software Engineering
Object Oriented Software Engineering
 
Cara membuat software dj
Cara membuat software djCara membuat software dj
Cara membuat software dj
 
How to build a debug view almost for free
How to build a debug view almost for freeHow to build a debug view almost for free
How to build a debug view almost for free
 
Coding java.txt
Coding java.txtCoding java.txt
Coding java.txt
 

Viewers also liked

Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzationEhtisham Ali
 
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...Andrey Gershun
 
Alasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScriptAlasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScriptAndrey Gershun
 
Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)Andrey Gershun
 
High Performance Front-End Development
High Performance Front-End DevelopmentHigh Performance Front-End Development
High Performance Front-End Developmentdrywallbmb
 
Spatialware_2_Sql08
Spatialware_2_Sql08Spatialware_2_Sql08
Spatialware_2_Sql08Mike Osbourn
 
Multidimensional model programming
Multidimensional model programmingMultidimensional model programming
Multidimensional model programmingSteve Xu
 
X query language reference
X query language referenceX query language reference
X query language referenceSteve Xu
 
Multi-thematic spatial databases
Multi-thematic spatial databasesMulti-thematic spatial databases
Multi-thematic spatial databasesConor Mc Elhinney
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developersllangit
 
Css introduction
Css introductionCss introduction
Css introductionSridhar P
 
Transact sql data definition language - ddl- reference
Transact sql data definition language - ddl- referenceTransact sql data definition language - ddl- reference
Transact sql data definition language - ddl- referenceSteve Xu
 

Viewers also liked (20)

Sql server ___________session3-normailzation
Sql server  ___________session3-normailzationSql server  ___________session3-normailzation
Sql server ___________session3-normailzation
 
SQL Server 2008 Spatial Data - Getting Started
SQL Server 2008 Spatial Data - Getting StartedSQL Server 2008 Spatial Data - Getting Started
SQL Server 2008 Spatial Data - Getting Started
 
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
AlaSQL библиотека для обработки JavaScript данных (презентация для ForntEnd 2...
 
Alasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScriptAlasql.js - SQL сервер на JavaScript
Alasql.js - SQL сервер на JavaScript
 
Module08
Module08Module08
Module08
 
Module03
Module03Module03
Module03
 
Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)Alasql - база данных SQL на JavaScript (MoscowJS)
Alasql - база данных SQL на JavaScript (MoscowJS)
 
Module07
Module07Module07
Module07
 
High Performance Front-End Development
High Performance Front-End DevelopmentHigh Performance Front-End Development
High Performance Front-End Development
 
Spatialware_2_Sql08
Spatialware_2_Sql08Spatialware_2_Sql08
Spatialware_2_Sql08
 
Multidimensional model programming
Multidimensional model programmingMultidimensional model programming
Multidimensional model programming
 
X query language reference
X query language referenceX query language reference
X query language reference
 
Multi-thematic spatial databases
Multi-thematic spatial databasesMulti-thematic spatial databases
Multi-thematic spatial databases
 
Module04
Module04Module04
Module04
 
SQL Server 2008 for Developers
SQL Server 2008 for DevelopersSQL Server 2008 for Developers
SQL Server 2008 for Developers
 
Css introduction
Css introductionCss introduction
Css introduction
 
Sql Server Data Tools - Codenamed JUNEAU
Sql Server Data Tools - Codenamed JUNEAUSql Server Data Tools - Codenamed JUNEAU
Sql Server Data Tools - Codenamed JUNEAU
 
Module01
Module01Module01
Module01
 
Module05
Module05Module05
Module05
 
Transact sql data definition language - ddl- reference
Transact sql data definition language - ddl- referenceTransact sql data definition language - ddl- reference
Transact sql data definition language - ddl- reference
 

Similar to Module06 (20)

Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsql
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15
 
Trigger
TriggerTrigger
Trigger
 
Trigger
TriggerTrigger
Trigger
 
Triggers
TriggersTriggers
Triggers
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Sql triggers
Sql triggersSql triggers
Sql triggers
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptx
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
 
Mca ii-dbms-u-v-transaction management
Mca ii-dbms-u-v-transaction managementMca ii-dbms-u-v-transaction management
Mca ii-dbms-u-v-transaction management
 
DOODB_LAB.pptx
DOODB_LAB.pptxDOODB_LAB.pptx
DOODB_LAB.pptx
 
triggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdftriggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdf
 
Exceptions Triggers function in SQL by Vasant Bhabad
Exceptions Triggers function in SQL by Vasant BhabadExceptions Triggers function in SQL by Vasant Bhabad
Exceptions Triggers function in SQL by Vasant Bhabad
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
 
Les08
Les08Les08
Les08
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Les09
Les09Les09
Les09
 
Les08
Les08Les08
Les08
 

Recently uploaded

BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17Celine George
 
Riti theory by Vamana Indian poetics.pptx
Riti theory by Vamana Indian poetics.pptxRiti theory by Vamana Indian poetics.pptx
Riti theory by Vamana Indian poetics.pptxDhatriParmar
 
Material Remains as Source of Ancient Indian History & Culture.ppt
Material Remains as Source of Ancient Indian History & Culture.pptMaterial Remains as Source of Ancient Indian History & Culture.ppt
Material Remains as Source of Ancient Indian History & Culture.pptBanaras Hindu University
 
AI Uses and Misuses: Academic and Workplace Applications
AI Uses and Misuses: Academic and Workplace ApplicationsAI Uses and Misuses: Academic and Workplace Applications
AI Uses and Misuses: Academic and Workplace ApplicationsStella Lee
 
Auchitya Theory by Kshemendra Indian Poetics
Auchitya Theory by Kshemendra Indian PoeticsAuchitya Theory by Kshemendra Indian Poetics
Auchitya Theory by Kshemendra Indian PoeticsDhatriParmar
 
POST ENCEPHALITIS case study Jitendra bhargav
POST ENCEPHALITIS case study  Jitendra bhargavPOST ENCEPHALITIS case study  Jitendra bhargav
POST ENCEPHALITIS case study Jitendra bhargavJitendra Bhargav
 
3.12.24 The Social Construction of Gender.pptx
3.12.24 The Social Construction of Gender.pptx3.12.24 The Social Construction of Gender.pptx
3.12.24 The Social Construction of Gender.pptxmary850239
 
DNA and RNA , Structure, Functions, Types, difference, Similarities, Protein ...
DNA and RNA , Structure, Functions, Types, difference, Similarities, Protein ...DNA and RNA , Structure, Functions, Types, difference, Similarities, Protein ...
DNA and RNA , Structure, Functions, Types, difference, Similarities, Protein ...AKSHAYMAGAR17
 
3.14.24 The Selma March and the Voting Rights Act.pptx
3.14.24 The Selma March and the Voting Rights Act.pptx3.14.24 The Selma March and the Voting Rights Act.pptx
3.14.24 The Selma March and the Voting Rights Act.pptxmary850239
 
Awards Presentation 2024 - March 12 2024
Awards Presentation 2024 - March 12 2024Awards Presentation 2024 - March 12 2024
Awards Presentation 2024 - March 12 2024bsellato
 
UNIT I Design Thinking and Explore.pptx
UNIT I  Design Thinking and Explore.pptxUNIT I  Design Thinking and Explore.pptx
UNIT I Design Thinking and Explore.pptxGOWSIKRAJA PALANISAMY
 
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdfPHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdfSumit Tiwari
 
BBA 205 BE UNIT 2 economic systems prof dr kanchan.pptx
BBA 205 BE UNIT 2 economic systems prof dr kanchan.pptxBBA 205 BE UNIT 2 economic systems prof dr kanchan.pptx
BBA 205 BE UNIT 2 economic systems prof dr kanchan.pptxProf. Kanchan Kumari
 
The basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptxThe basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptxheathfieldcps1
 
The OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
The OERs: Transforming Education for Sustainable Future by Dr. Sarita AnandThe OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
The OERs: Transforming Education for Sustainable Future by Dr. Sarita AnandDr. Sarita Anand
 
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdfArti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdfwill854175
 
30-de-thi-vao-lop-10-mon-tieng-anh-co-dap-an.doc
30-de-thi-vao-lop-10-mon-tieng-anh-co-dap-an.doc30-de-thi-vao-lop-10-mon-tieng-anh-co-dap-an.doc
30-de-thi-vao-lop-10-mon-tieng-anh-co-dap-an.docdieu18
 

Recently uploaded (20)

BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
How to Customise Quotation's Appearance Using PDF Quote Builder in Odoo 17
 
Riti theory by Vamana Indian poetics.pptx
Riti theory by Vamana Indian poetics.pptxRiti theory by Vamana Indian poetics.pptx
Riti theory by Vamana Indian poetics.pptx
 
t-test Parametric test Biostatics and Research Methodology
t-test Parametric test Biostatics and Research Methodologyt-test Parametric test Biostatics and Research Methodology
t-test Parametric test Biostatics and Research Methodology
 
Material Remains as Source of Ancient Indian History & Culture.ppt
Material Remains as Source of Ancient Indian History & Culture.pptMaterial Remains as Source of Ancient Indian History & Culture.ppt
Material Remains as Source of Ancient Indian History & Culture.ppt
 
AI Uses and Misuses: Academic and Workplace Applications
AI Uses and Misuses: Academic and Workplace ApplicationsAI Uses and Misuses: Academic and Workplace Applications
AI Uses and Misuses: Academic and Workplace Applications
 
Auchitya Theory by Kshemendra Indian Poetics
Auchitya Theory by Kshemendra Indian PoeticsAuchitya Theory by Kshemendra Indian Poetics
Auchitya Theory by Kshemendra Indian Poetics
 
POST ENCEPHALITIS case study Jitendra bhargav
POST ENCEPHALITIS case study  Jitendra bhargavPOST ENCEPHALITIS case study  Jitendra bhargav
POST ENCEPHALITIS case study Jitendra bhargav
 
3.12.24 The Social Construction of Gender.pptx
3.12.24 The Social Construction of Gender.pptx3.12.24 The Social Construction of Gender.pptx
3.12.24 The Social Construction of Gender.pptx
 
DNA and RNA , Structure, Functions, Types, difference, Similarities, Protein ...
DNA and RNA , Structure, Functions, Types, difference, Similarities, Protein ...DNA and RNA , Structure, Functions, Types, difference, Similarities, Protein ...
DNA and RNA , Structure, Functions, Types, difference, Similarities, Protein ...
 
3.14.24 The Selma March and the Voting Rights Act.pptx
3.14.24 The Selma March and the Voting Rights Act.pptx3.14.24 The Selma March and the Voting Rights Act.pptx
3.14.24 The Selma March and the Voting Rights Act.pptx
 
Awards Presentation 2024 - March 12 2024
Awards Presentation 2024 - March 12 2024Awards Presentation 2024 - March 12 2024
Awards Presentation 2024 - March 12 2024
 
UNIT I Design Thinking and Explore.pptx
UNIT I  Design Thinking and Explore.pptxUNIT I  Design Thinking and Explore.pptx
UNIT I Design Thinking and Explore.pptx
 
ANOVA Parametric test: Biostatics and Research Methodology
ANOVA Parametric test: Biostatics and Research MethodologyANOVA Parametric test: Biostatics and Research Methodology
ANOVA Parametric test: Biostatics and Research Methodology
 
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdfPHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
PHARMACOGNOSY CHAPTER NO 5 CARMINATIVES AND G.pdf
 
BBA 205 BE UNIT 2 economic systems prof dr kanchan.pptx
BBA 205 BE UNIT 2 economic systems prof dr kanchan.pptxBBA 205 BE UNIT 2 economic systems prof dr kanchan.pptx
BBA 205 BE UNIT 2 economic systems prof dr kanchan.pptx
 
The basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptxThe basics of sentences session 8pptx.pptx
The basics of sentences session 8pptx.pptx
 
The OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
The OERs: Transforming Education for Sustainable Future by Dr. Sarita AnandThe OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
The OERs: Transforming Education for Sustainable Future by Dr. Sarita Anand
 
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdfArti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
Arti Languages Pre Seed Send Ahead Pitchdeck 2024.pdf
 
30-de-thi-vao-lop-10-mon-tieng-anh-co-dap-an.doc
30-de-thi-vao-lop-10-mon-tieng-anh-co-dap-an.doc30-de-thi-vao-lop-10-mon-tieng-anh-co-dap-an.doc
30-de-thi-vao-lop-10-mon-tieng-anh-co-dap-an.doc
 

Module06

Editor's Notes

  1. 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.
  2. 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. 
  3. 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.
  4. 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.
  5. 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.
  6. 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’.
  7. 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.
  8. 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.
  9. 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.
  10. 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
  11. 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’