SlideShare une entreprise Scribd logo
1  sur  5
TRIGGER
First And Most important things come to everyone mind is that “What is trigger and why
we use it????” .So trigger is nothing but just like a special kind of Store Procedure
“Trigger is special kind of store procedure or stored programs, which is automatically fired
or executed when some events (Insert, Delete, and Update) occur. “
If you write a trigger for insert operation on a table, after firing the trigger, it creates a table
named “INSERTED” in the memory. Then it performs the insert operation and after that the
statements inside the trigger executes. We can query the “INSERTED” table to manipulate
or use the inserted row/s from the trigger.
Similarly, if you write a trigger for delete operation on a table, it creates a table in memory
named “DELETED” and then deletes the row.
Why and when use trigger:
We use trigger when we want some event should happen automatically on certain
desirable scenario.
Let’s take an example.
You have a table which changes frequently, now you want to know how many times and
when did these changes take place.
In that case you can create a trigger which will insert desired data in any other table
whenever any changes in your main table occur.
Types of Triggers
In Sql Server we can create 3 types of triggers
1 Data Definition Language (DDL) triggers,
2. Data Manipulation Language (DML) triggers,
3. Logon triggers.
1. DDL Triggers
In SQL Server we can create triggers on DDL statements (like CREATE, ALTER, and DROP)
and certain system defined stored procedures that perform DDL-like operations.
2. DML Triggers
In SQL Server we can create triggers on DML statements (like INSERT, UPDATE, and
DELETE) and stored procedures that perform DML-like operations. DML Triggers are of
two types
After trigger (using FOR/AFTER CLAUSE)
This type of trigger fires after SQL Server finish the execution of the action successfully that
fired it.
Example : If you insert record/row in a table then the trigger related/associated with the
insert event on this table will fire only after the row passes all the constraints, like as
primary key constraint, and some rules. If the record/row insertion fails, SQL Server will
not fire the After Trigger.
Instead of Trigger (using INSTEAD OF CLAUSE)
This type of trigger fires before SQL Server starts the execution of the action that fired it.
This is differ from the AFTER trigger, which fires after the action that caused it to fire. We
can have an INSTEAD OF insert/update/delete trigger on a table that successfully executed
but does not include the actual insert/update/delete to the table.
Example : If you insert record/row in a table then the trigger related/associated with the
insert event on this table will fire before the row passes all the constraints, such as primary
key constraint and some rules. If the record/row insertion fails, SQL Server will fire the
Instead of Trigger.
3.Logon Triggers
Logon triggers are special type of trigger that fire when LOGON event of Sql Server is
raised. This event is raised when a user session is being established with Sql Server that is
made after the authentication phase finishes, but before the user session is actually
established. Hence, all messages that we define in the trigger such as error messages, will
be redirected to the SQL Server error log. Logon triggers do not fire if authentication fails.
We can use these triggers to audit and control server sessions, such as to track login
activity or limit the number of sessions for a specific login.
In Short Different Type of triggers are:
1) DML
a) Instead of Trigger: Instead of trigger are fired in place of the triggering action such as an
insert, update, or delete
b) After Trigger: After trigger execute following the triggering action ,such as an
insert,update,or delete.
2) DDL Trigger
This type of trigger is fired against DDL statements like Drop Table, Create Table, Or Alter
Table,DDL Triggers are always after Triggers
3) Logon trigger
This type of trigger is fired against a LOGON event before a user session is established to
the SQL Server
Syntax: Very easy and useful syntax of trigger
CREATE TRIGGER triggerName ON table
AFTER INSERT |After Delete |After Upadte
AS BEGIN
INSERT INTO dbo.UserHistory............
END
Example:
1. Create a Table
CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)
2. Insert Records in It:
INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);
3. Create another table to store transaction records like records of insert delete
update on Employee_Test Table
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
4. Now create trigger:
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test]
FOR INSERT
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);
select @empid=i.Emp_ID from inserted i;
select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
set @audit_action='Inserted Record -- After Insert Trigger.';
insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());
PRINT 'AFTER INSERT trigger fired.'
GO
5. Now insert one record in Employee_Test
insert into Employee_Test values('Ravi',1500);
6. After That see Employee_Test_Audit table
Select * from Employee_Test_Audit
Good luck!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Contenu connexe

En vedette

En vedette (13)

Charged inc investment prospectus - artie
Charged inc   investment prospectus - artieCharged inc   investment prospectus - artie
Charged inc investment prospectus - artie
 
Ficha de Santa rosa del Abuna
Ficha de Santa rosa del AbunaFicha de Santa rosa del Abuna
Ficha de Santa rosa del Abuna
 
Anuario estadístico de Salud 2009
Anuario estadístico de Salud 2009Anuario estadístico de Salud 2009
Anuario estadístico de Salud 2009
 
Beni
BeniBeni
Beni
 
How to create Store Procedure
How to create Store ProcedureHow to create Store Procedure
How to create Store Procedure
 
Function
FunctionFunction
Function
 
Fetal chest
Fetal chestFetal chest
Fetal chest
 
Gineth o
Gineth oGineth o
Gineth o
 
Index in sql server
Index in sql serverIndex in sql server
Index in sql server
 
โครงงานคอมพิวเตอร์
โครงงานคอมพิวเตอร์โครงงานคอมพิวเตอร์
โครงงานคอมพิวเตอร์
 
Absolute beginnersseriesforwindowsphone8
Absolute beginnersseriesforwindowsphone8Absolute beginnersseriesforwindowsphone8
Absolute beginnersseriesforwindowsphone8
 
Chorio
ChorioChorio
Chorio
 
merrick differential peice rate plan..(piece wage plan)
merrick differential peice rate plan..(piece wage plan)merrick differential peice rate plan..(piece wage plan)
merrick differential peice rate plan..(piece wage plan)
 

Similaire à Trigger

Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersAlexey Furmanov
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15Syed Asrarali
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptxKhngNguyn81
 
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 16Thuan Nguyen
 
triggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdftriggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdfsaikumar580678
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academythewebsacademy
 
Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsqlArun Sial
 
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 managementRai University
 
11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)Simarjit Mann
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersAbdul Rahman Sherzad
 

Similaire à Trigger (20)

Sql triggers
Sql triggersSql triggers
Sql triggers
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Trigger
TriggerTrigger
Trigger
 
Module06
Module06Module06
Module06
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15
 
Triggers.PPTX
Triggers.PPTXTriggers.PPTX
Triggers.PPTX
 
Triggers
TriggersTriggers
Triggers
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptx
 
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
 
triggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdftriggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdf
 
Oracle Database Trigger
Oracle Database TriggerOracle Database Trigger
Oracle Database Trigger
 
Triggers
TriggersTriggers
Triggers
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
 
Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsql
 
T-SQL & Triggers
T-SQL & TriggersT-SQL & Triggers
T-SQL & Triggers
 
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
 
11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)11303 dbms chap_02_triggers (2)
11303 dbms chap_02_triggers (2)
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 

Dernier

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 

Dernier (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 

Trigger

  • 1. TRIGGER First And Most important things come to everyone mind is that “What is trigger and why we use it????” .So trigger is nothing but just like a special kind of Store Procedure “Trigger is special kind of store procedure or stored programs, which is automatically fired or executed when some events (Insert, Delete, and Update) occur. “ If you write a trigger for insert operation on a table, after firing the trigger, it creates a table named “INSERTED” in the memory. Then it performs the insert operation and after that the statements inside the trigger executes. We can query the “INSERTED” table to manipulate or use the inserted row/s from the trigger. Similarly, if you write a trigger for delete operation on a table, it creates a table in memory named “DELETED” and then deletes the row. Why and when use trigger: We use trigger when we want some event should happen automatically on certain desirable scenario. Let’s take an example. You have a table which changes frequently, now you want to know how many times and when did these changes take place. In that case you can create a trigger which will insert desired data in any other table whenever any changes in your main table occur. Types of Triggers In Sql Server we can create 3 types of triggers 1 Data Definition Language (DDL) triggers, 2. Data Manipulation Language (DML) triggers, 3. Logon triggers. 1. DDL Triggers In SQL Server we can create triggers on DDL statements (like CREATE, ALTER, and DROP) and certain system defined stored procedures that perform DDL-like operations.
  • 2. 2. DML Triggers In SQL Server we can create triggers on DML statements (like INSERT, UPDATE, and DELETE) and stored procedures that perform DML-like operations. DML Triggers are of two types After trigger (using FOR/AFTER CLAUSE) This type of trigger fires after SQL Server finish the execution of the action successfully that fired it. Example : If you insert record/row in a table then the trigger related/associated with the insert event on this table will fire only after the row passes all the constraints, like as primary key constraint, and some rules. If the record/row insertion fails, SQL Server will not fire the After Trigger. Instead of Trigger (using INSTEAD OF CLAUSE) This type of trigger fires before SQL Server starts the execution of the action that fired it. This is differ from the AFTER trigger, which fires after the action that caused it to fire. We can have an INSTEAD OF insert/update/delete trigger on a table that successfully executed but does not include the actual insert/update/delete to the table. Example : If you insert record/row in a table then the trigger related/associated with the insert event on this table will fire before the row passes all the constraints, such as primary key constraint and some rules. If the record/row insertion fails, SQL Server will fire the Instead of Trigger. 3.Logon Triggers Logon triggers are special type of trigger that fire when LOGON event of Sql Server is raised. This event is raised when a user session is being established with Sql Server that is made after the authentication phase finishes, but before the user session is actually established. Hence, all messages that we define in the trigger such as error messages, will be redirected to the SQL Server error log. Logon triggers do not fire if authentication fails. We can use these triggers to audit and control server sessions, such as to track login activity or limit the number of sessions for a specific login. In Short Different Type of triggers are: 1) DML a) Instead of Trigger: Instead of trigger are fired in place of the triggering action such as an
  • 3. insert, update, or delete b) After Trigger: After trigger execute following the triggering action ,such as an insert,update,or delete. 2) DDL Trigger This type of trigger is fired against DDL statements like Drop Table, Create Table, Or Alter Table,DDL Triggers are always after Triggers 3) Logon trigger This type of trigger is fired against a LOGON event before a user session is established to the SQL Server Syntax: Very easy and useful syntax of trigger CREATE TRIGGER triggerName ON table AFTER INSERT |After Delete |After Upadte AS BEGIN INSERT INTO dbo.UserHistory............ END Example: 1. Create a Table CREATE TABLE Employee_Test ( Emp_ID INT Identity, Emp_name Varchar(100), Emp_Sal Decimal (10,2) ) 2. Insert Records in It:
  • 4. INSERT INTO Employee_Test VALUES ('Anees',1000); INSERT INTO Employee_Test VALUES ('Rick',1200); INSERT INTO Employee_Test VALUES ('John',1100); INSERT INTO Employee_Test VALUES ('Stephen',1300); INSERT INTO Employee_Test VALUES ('Maria',1400); 3. Create another table to store transaction records like records of insert delete update on Employee_Test Table CREATE TABLE Employee_Test_Audit ( Emp_ID int, Emp_name varchar(100), Emp_Sal decimal (10,2), Audit_Action varchar(100), Audit_Timestamp datetime ) 4. Now create trigger: CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test] FOR INSERT AS declare @empid int; declare @empname varchar(100); declare @empsal decimal(10,2);
  • 5. declare @audit_action varchar(100); select @empid=i.Emp_ID from inserted i; select @empname=i.Emp_Name from inserted i; select @empsal=i.Emp_Sal from inserted i; set @audit_action='Inserted Record -- After Insert Trigger.'; insert into Employee_Test_Audit (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) values(@empid,@empname,@empsal,@audit_action,getdate()); PRINT 'AFTER INSERT trigger fired.' GO 5. Now insert one record in Employee_Test insert into Employee_Test values('Ravi',1500); 6. After That see Employee_Test_Audit table Select * from Employee_Test_Audit Good luck!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!