SlideShare a Scribd company logo
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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

More Related Content

Viewers also liked

Charged inc investment prospectus - artie
Charged inc   investment prospectus - artieCharged inc   investment prospectus - artie
Charged inc investment prospectus - artieDrinkCharged
 
Ficha de Santa rosa del Abuna
Ficha de Santa rosa del AbunaFicha de Santa rosa del Abuna
Ficha de Santa rosa del Abuna
Richard Suárez Velarde
 
Anuario estadístico de Salud 2009
Anuario estadístico de Salud 2009Anuario estadístico de Salud 2009
Anuario estadístico de Salud 2009
Richard Suárez Velarde
 
Beni
BeniBeni
How to create Store Procedure
How to create Store ProcedureHow to create Store Procedure
How to create Store Procedure
Durgaprasad Yadav
 
Function
FunctionFunction
Index in sql server
Index in sql serverIndex in sql server
Index in sql server
Durgaprasad Yadav
 
โครงงานคอมพิวเตอร์
โครงงานคอมพิวเตอร์โครงงานคอมพิวเตอร์
โครงงานคอมพิวเตอร์uoropo01
 
Absolute beginnersseriesforwindowsphone8
Absolute beginnersseriesforwindowsphone8Absolute beginnersseriesforwindowsphone8
Absolute beginnersseriesforwindowsphone8Mahisa Dyan Diptya
 
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)
kulmitsingh
 

Viewers also liked (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)
 

Similar to Trigger

Sql triggers
Sql triggersSql triggers
Sql triggers
Chandan Banerjee
 
Database Triggers
Database TriggersDatabase Triggers
Database Triggers
Aliya Saldanha
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
Alexey Furmanov
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
Zaid227349
 
Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15Syed Asrarali
 
Triggers.PPTX
Triggers.PPTXTriggers.PPTX
Triggers.PPTX
ansariparveen06
 
Triggers
TriggersTriggers
Triggers
Pooja Dixit
 
Lab07_Triggers.pptx
Lab07_Triggers.pptxLab07_Triggers.pptx
Lab07_Triggers.pptx
KhngNguyn81
 
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
Thuan Nguyen
 
triggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdftriggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdf
saikumar580678
 
Oracle Database Trigger
Oracle Database TriggerOracle Database Trigger
Oracle Database Trigger
Eryk Budi Pratama
 
Triggers
TriggersTriggers
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
thewebsacademy
 
Triggers in plsql
Triggers in plsqlTriggers in plsql
Triggers in plsql
Arun Sial
 
T-SQL & Triggers
T-SQL & TriggersT-SQL & Triggers
T-SQL & Triggers
Ayesha Maqsood
 
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
Rai 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 Schedulers
Abdul Rahman Sherzad
 

Similar to 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
 

Recently uploaded

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 

Recently uploaded (20)

Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 

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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!