Triggers - SQL Server: What Is A Trigger

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Not quite what you are looking for?

You may want to try: ×


• SQL Triggers – An Introduction
• Overview of SQL Server database Triggers
highlights off

13,968,803 members Sign in

triggers in sql

articles quick answers discussions features community help

Articles » Database » Database » SQL Server

Triggers -- SQL Server


Sudipta Chaudhari, 26 Apr 2008

 4.84 (246 votes) Rate this:

This article gives a brief introduction about Triggers in SQL Server 2000/2005.

Introduction
This article gives a brief introduction about Triggers in SQL Server 2000/2005.

What is a Trigger
A trigger is a special kind of a stored procedure that executes in response to certain action on the table like insertion,
deletion or updation of data. It is a database object which is bound to a table and is executed automatically. You can’t
explicitly invoke triggers. The only way to do this is by performing the required action on the table that they are assigned
to.
Types Of Triggers
There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three
types of triggers and hybrids that come from mixing and matching the events and timings that fire them. Basically,
triggers are classified into two main types:

i. After Triggers (For Triggers)


ii. Instead Of Triggers

(i) After Triggers


These triggers run after an insert, update or delete on a table. They are not supported for views.
AFTER TRIGGERS can be classified further into three types as:

a. AFTER INSERT Trigger


b. AFTER UPDATE Trigger
c. AFTER DELETE Trigger

Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on this table, I will be
attaching several triggers.

Hide Copy Code

CREATE TABLE Employee_Test


(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

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);

I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into another audit table. The
main purpose of this audit table is to record the changes in the main table. This can be thought of as a generic audit
trigger.

Now, create the audit table as:

Hide Copy Code

CREATE TABLE Employee_Test_Audit


(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
(a) After Insert Trigger

This trigger is fired after an INSERT on the table. Let’s create the trigger as:

Hide Copy Code

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

The CREATE TRIGGER statement is used to create the trigger. The ON clause specifies the table name on which the
trigger is to be attached. The FOR INSERT specifies that this is an AFTER INSERT trigger. In place of FOR INSERT,
AFTER INSERT can be used. Both of them mean the same.
In the trigger body, table named inserted has been used. This table is a logical table and contains the row that has been
inserted. I have selected the fields from the logical inserted table from the row that has been inserted into different
variables, and finally inserted those values into the Audit table.

To see the newly created trigger in action, let's insert a row into the main table as:

Hide Copy Code

insert into Employee_Test values('Chris',1500);

Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached to this table
has inserted the record into the Employee_Test_Audit as:

Hide Copy Code

6 Chris 1500.00 Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700

(b) AFTER UPDATE Trigger


This trigger is fired after an update on the table. Let’s create the trigger as:

Hide Copy Code

CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test]


FOR UPDATE
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;

if update(Emp_Name)
set @audit_action='Updated Record -- After Update Trigger.';
if update(Emp_Sal)
set @audit_action='Updated Record -- After Update 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 UPDATE Trigger fired.'


GO

The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table. There is no logical
table updated like the logical table inserted. We can obtain the updated value of a field from the
update(column_name) function. In our trigger, we have used, if update(Emp_Name) to check if the column
Emp_Name has been updated. We have similarly checked the column Emp_Sal for an update.
Let’s update a record column and see what happens.

Hide Copy Code

update Employee_Test set Emp_Sal=1550 where Emp_ID=6

This inserts the row into the audit table as:

Hide Copy Code

6 Chris 1550.00 Updated Record -- After Update Trigger. 2008-04-26 12:38:11.843

(c) AFTER DELETE Trigger

This trigger is fired after a delete on the table. Let’s create the trigger as:

Hide Copy Code

CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test]


AFTER DELETE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

select @empid=d.Emp_ID from deleted d;


select @empname=d.Emp_Name from deleted d;
select @empsal=d.Emp_Sal from deleted d;
set @audit_action='Deleted -- After Delete 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 DELETE TRIGGER fired.'


GO

In this trigger, the deleted record’s data is picked from the logical deleted table and inserted into the audit table. Let’s
fire a delete on the main table. A record has been inserted into the audit table as:

Hide Copy Code

6 Chris 1550.00 Deleted -- After Delete Trigger. 2008-04-26 12:52:13.867

All the triggers can be enabled/disabled on the table using the statement:

Hide Copy Code

ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL

Specific Triggers can be enabled or disabled as:

Hide Copy Code

ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete

This disables the After Delete Trigger named trgAfterDelete on the specified table.

(ii) Instead Of Triggers


These can be used as an interceptor for anything that anyone tried to do on our table or view. If you define an Instead Of
trigger on a table for the Delete operation, they try to delete rows, and they will not actually get deleted (unless you
issue another delete instruction from within the trigger).

INSTEAD OF TRIGGERS can be classified further into three types as:

a. INSTEAD OF INSERT Trigger


b. INSTEAD OF UPDATE Trigger
c. INSTEAD OF DELETE Trigger

Let’s create an Instead Of Delete Trigger as:

Hide Shrink Copy Code

CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test]


INSTEAD OF DELETE
AS
declare @emp_id int;
declare @emp_name varchar(100);
declare @emp_sal int;

select @emp_id=d.Emp_ID from deleted d;


select @emp_name=d.Emp_Name from deleted d;
select @emp_sal=d.Emp_Sal from deleted d;

BEGIN
if(@emp_sal>1200)
begin
RAISERROR('Cannot delete where salary > 1200',16,1);
ROLLBACK;
end
else
begin
delete from Employee_Test where Emp_ID=@emp_id;
COMMIT;
insert into
Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,
Audit_Timestamp)
values(@emp_id,@emp_name,@emp_sal,
'Deleted -- Instead Of Delete Trigger.',getdate());
PRINT 'Record Deleted -- Instead Of Delete Trigger.'
end
END
GO

This trigger will prevent the deletion of records from the table where Emp_Sal > 1200. If such a record is deleted, the
Instead Of Trigger will rollback the transaction, otherwise the transaction will be committed. Now, let’s try to delete a
record with the Emp_Sal >1200 as:

Hide Copy Code

delete from Employee_Test where Emp_ID=4

This will print an error message as defined in the RAISE ERROR statement as:
Hide Copy Code

Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfDelete, Line 15


Cannot delete where salary > 1200

And this record will not be deleted.

In a similar way, you can code Instead Of Insert and Instead Of Update triggers on your tables.

Conclusion
In this article, I took a brief introduction of triggers, explained the various kinds of triggers – After Triggers and Instead Of
Triggers along with their variants and explained how each of them works. I hope you will get a clear understanding about
the Triggers in SQL Server and their usage.

License
This article, along with any associated source code and files, is
licensed under The Code Project Open License (CPOL)
Share

About the Author


Sudipta Chaudhari
Architect
India

Myself Sudipta Chaudhari and I am B.TECH in Computer Science by education, Software Developer by profession and
Senior Technical Lead by designation. I have 13+ yrs of professional work experience and have multiple onsite/client site
visit experiences. I am working with one of the largest reputed MNC in India.

I have extensive experience working on Microsoft .NET technologies – Azure, ASP.NET Web API, ASP.NET MVC, C#, SQL
Server and JavaScript frameworks like jQuery, Angular 4 etc. I am also a SCRUM Master.

I can be contacted for full time job opportunities as a SENIOR TECHNICAL ARCHITECT/ TECHNICAL MANAGER /
PROJECT MANAGER.

I can be reached at : [email protected]

For latest articles and updates, please visit by website/blog : http://sudiptachaudhari.com


You may also be interested in...
Win32 Thread Pools and C++11 : A quick wrapper

PDF417 Barcode Encoder .NET Class Library and Demo App

Comments and Discussions

You must Sign In to use this message board.

Search Comments

Spacing Relaxed    Layout Open All    Per page 25  Update

First Prev Next

Are you a time traveller? Member 10196338 8-Jun-18 5:24 

Hide Copy Code

Your maths does not appear to add up. Working since 2008. 13 years professional
experience - therefore at time of writing it must have been 2021. Are you a time
traveller?

Sign In · View Thread

trigger Member 13773357 10-Apr-18 21:21 

very useful

Sign In · View Thread

Triggers in Sql Server Member 10035917 27-Mar-17 20:02 


How to write a trigger to update one column of a table based on values of another columns?

Sign In · View Thread

Re: Triggers in Sql Server Koda Naresh 27-Dec-17 22:46 

Go with Instead of trigger.

Sign In · View Thread

CODE PROJECT TRIGGER SQL SERVER BY mariavincentshyam 13-Apr-16 21:23 


s.india Software Developer (Senior)

I am very thankful to the s.india Software Developer (Senior). Because I have no idea about sql trigger even though
4 years of PHP experience. But your SQL Trigger tutorial is very very very very helpful for me.

Sign In · View Thread 5.00/5 (1 vote)

Typo error in What is a Trigger section Ashish Shuklaa 4-Apr-16 8:16 

it should be "by performing the required action on the table" instead of "by performing the required action no the
table".

Sign In · View Thread

thanks for sharing very informative saqib_amin 5-Jan-16 22:54 


examples

thanks for sharing very informative examples

Sign In · View Thread

Thanks plenty Member 10807560 1-Aug-15 7:34 

I want to thank the person that wrote this article so much, because I had never understood triggers all through
school, and now I have a thorough understanding of then, all thanks to this article!

Sign In · View Thread

Its really nice Article... Member 10989758 1-Jul-15 22:54 

Its really nice Article...


Sign In · View Thread

Great Member 11628107 22-Apr-15 17:15 

Really it is very useful.

Sign In · View Thread

thanks Iglesk 17-Apr-15 19:20 

Thank you sir,


this war really helpful really thanks
wish you all the best.

Sign In · View Thread

My vote of 1 (should really be -1 !!) Marc Scheuner 17-Apr-15 2:03 

This code you're presenting here is HORRIBLY BAD and factually wrong.....

Consider this line:

select @empid=i.Emp_ID from inserted i;

If your SQL INSERT statement inserts 10 or 20 rows at once (using a SELECT from another table), then this trigger
will be called once, and the Inserted pseudo table will contain 10 or 20 rows.

Which one of those do you think you're getting with your SELECT statement?? It's undetermined - you'll get one,
arbitrary row - and you plainly ignore all others!!

This code should be TOSSED OUT right now and REWRITTEN entirely to take into account that a trigger CAN (and
WILL!) get multiple rows in its Inserted (and Deleted) pseudo tables!

=============================
Marc Scheuner, Berne, Switzerland
mscheuner - at - gmail.com
May The Source Be With You!

Sign In · View Thread 5.00/5 (2 votes)

Re: My vote of 1 (should really be -1 !!) Member 11022691 23-Jul-16 4:44 

Mind sharing the correct way of doing that?

Sign In · View Thread
Member 8979127 25-Feb-15 22:45 
Thank you. Excellent as always!

Thank you. Excellent as always!

Sign In · View Thread

Great article Member 11323667 19-Feb-15 21:26 

thanks for your great article. before reading this article i had no idea whats is the triggers are. i have done the
triggers for my degree,but i have totally forgot those stuff. thank you very much for this great article. i hope you
will publish those kind of articles future. you are great.thank you

Sign In · View Thread

Triggers Member(Jilby) 16-Feb-15 20:00 


11024007

Thanks...

Sign In · View Thread

My vote of 5 Pratik Bhuva 15-Dec-14 1:53 

Short And Sweet Explanation.


Thanks For Sharing.

Sign In · View Thread

Thank you!!! RaviCG 26-Nov-14 3:06 

Thank you so much..


This article is very essay to understand.

Sign In · View Thread

For multiple rows Tripti Santikary 7-Nov-14 0:44 

This is very good artical and easy to understand.But may have multiple rows to insert or update or delete from
store procedure,

then it works properly or not? What happen in this situation.

Sign In · View Thread

Re: For multiple rows satyajit mohanta 18-Nov-14 1:38 


It will work fine in these case also. It's row based operation. So, the corresponding trigger query will be
executed no of times equal to no of rows affected.

Sign In · View Thread

Trigger Based km@123 5-Nov-14 21:30 

wherever used Trigger

Sign In · View Thread

no update of trigger action tabled Member 11077161 18-Sep-14 21:06 

thje triggers are being made just fine but when i am trying to look for data in th trigger_action table i am not
getting the corre3ct inserted data , i am getting the last row of my table

can u plzz tell me how to get the data that i insert into table or deleted data from it

Sign In · View Thread

Good explanation pallelokanathareddy 12-Aug-14 0:07 

I was about to add an article related to triggers, before doing so i got this article. Its very good and well explained.
You can read sql interview questions and answers
or directly check sql triggers interview questions and answers[^]

Sign In · View Thread 5.00/5 (1 vote)

Triggers Member 10898768 21-Jun-14 18:13 

Having created a trigger which logs the actions in a table called event_logs that includes the following data; the
user, date/time, attempt type and view name. (The attempt_type and view name data must not be hard coded. This
means that the system should provide those two details when a drop action is attempted - I have got this wrong
somewhere, can anybody please help me? Thanks
This is the code so far:
IF OBJECT_ID ('event_log') IS NOT NULL
DROP TABLE dbo.event_log

CREATE TABLE event_log


(
username VARCHAR(20),
event_type CHAR(1),
event_time SMALLDATETIME,
table_name VARCHAR(20)
)

GO

IF OBJECT_ID ('TRG_PREVENT_VIEW_DROP') IS NOT NULL


DROP TRIGGER TRG_PREVENT_VIEW_DROP

GO

CREATE TRIGGER TRG_PREVENT_VIEW_DROP


ON DATABASE FOR DROP_TABLE, ALTER_TABLE, DROP_VIEW, ALTER_VIEW

AS

PRINT 'ALTER or DROP action ATTEMPTED'


PRINT 'You do not have permission'
ROLLBACK TRANSACTION

Sign In · View Thread

My vote of 3 Member 4396634 1-May-14 1:04 

gd

Sign In · View Thread

Last Visit: 15-Apr-19 21:38     Last Update: 15-Apr-19 21:38 Refresh 1 2 3 4 5 Next »

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant   


Admin   

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile Layout: Article Copyright 2008 by Sudipta Chaudhari
Web05 | 2.8.190416.1 | Last Updated 26 Apr 2008 fixed | fluid Everything else Copyright © CodeProject, 1999-2019

You might also like