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

More Related Content

Viewers also liked

Charged inc investment prospectus - artie
Charged inc   investment prospectus - artieCharged inc   investment prospectus - artie
Charged inc investment prospectus - artie
DrinkCharged
 
โครงงานคอมพิวเตอร์
โครงงานคอมพิวเตอร์โครงงานคอมพิวเตอร์
โครงงานคอมพิวเตอร์
uoropo01
 
Absolute beginnersseriesforwindowsphone8
Absolute beginnersseriesforwindowsphone8Absolute beginnersseriesforwindowsphone8
Absolute beginnersseriesforwindowsphone8
Mahisa Dyan Diptya
 

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

Intro to tsql unit 15
Intro to tsql   unit 15Intro to tsql   unit 15
Intro to tsql unit 15
Syed Asrarali
 
triggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdftriggeroracle-eryk-130621201822-phpapp01.pdf
triggeroracle-eryk-130621201822-phpapp01.pdf
saikumar580678
 
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

會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
ashishpaul799
 

Recently uploaded (20)

The Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptxThe Ball Poem- John Berryman_20240518_001617_0000.pptx
The Ball Poem- John Berryman_20240518_001617_0000.pptx
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Discover the Dark Web .pdf InfosecTrain
Discover the Dark Web .pdf  InfosecTrainDiscover the Dark Web .pdf  InfosecTrain
Discover the Dark Web .pdf InfosecTrain
 
REPRODUCTIVE TOXICITY STUDIE OF MALE AND FEMALEpptx
REPRODUCTIVE TOXICITY  STUDIE OF MALE AND FEMALEpptxREPRODUCTIVE TOXICITY  STUDIE OF MALE AND FEMALEpptx
REPRODUCTIVE TOXICITY STUDIE OF MALE AND FEMALEpptx
 
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
 
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...Navigating the Misinformation Minefield: The Role of Higher Education in the ...
Navigating the Misinformation Minefield: The Role of Higher Education in the ...
 
Behavioral-sciences-dr-mowadat rana (1).pdf
Behavioral-sciences-dr-mowadat rana (1).pdfBehavioral-sciences-dr-mowadat rana (1).pdf
Behavioral-sciences-dr-mowadat rana (1).pdf
 
factors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptxfactors influencing drug absorption-final-2.pptx
factors influencing drug absorption-final-2.pptx
 
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdfPost Exam Fun(da) Intra UEM General Quiz - Finals.pdf
Post Exam Fun(da) Intra UEM General Quiz - Finals.pdf
 
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdfPost Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
MichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdfMichaelStarkes_UncutGemsProjectSummary.pdf
MichaelStarkes_UncutGemsProjectSummary.pdf
 
ppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyesppt your views.ppt your views of your college in your eyes
ppt your views.ppt your views of your college in your eyes
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 
Word Stress rules esl .pptx
Word Stress rules esl               .pptxWord Stress rules esl               .pptx
Word Stress rules esl .pptx
 
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
 
An Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptxAn Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptx
 
Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 2024Capitol Tech Univ Doctoral Presentation -May 2024
Capitol Tech Univ Doctoral Presentation -May 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!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!