Click here to Skip to main content
15,861,168 members
Articles / Database Development / SQL Server

Triggers -- SQL Server

Rate me:
Please Sign up or sign in to vote.
4.84/5 (246 votes)
26 Apr 2008CPOL4 min read 1.7M   232   123
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:

  1. After Triggers (For Triggers)
  2. 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:

  1. AFTER INSERT Trigger
  2. AFTER UPDATE Trigger
  3. 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.

SQL
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:

SQL
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:

SQL
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:

SQL
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:

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:

SQL
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.

SQL
update Employee_Test set Emp_Sal=1550 where Emp_ID=6

This inserts the row into the audit table as:

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:

SQL
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:

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:

SQL
ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL

Specific Triggers can be enabled or disabled as:

SQL
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:

  1. INSTEAD OF INSERT Trigger
  2. INSTEAD OF UPDATE Trigger
  3. INSTEAD OF DELETE Trigger

Let’s create an Instead Of Delete Trigger as:

SQL
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:

SQL
delete from Employee_Test where Emp_ID=4

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

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)


Written By
India India
Sudipta Chaudhari is having 14+ yrs of professional full stack software design & development experience with multiple onsite/client site visit experiences.

He has extensive experience working on – REACT, C#, .NET Core, Angular, AZURE, ASP.NET Web API, ASP.NET MVC, WPF, SQL Server, JQuery to name a few. He also has experience as a SCRUM Master.

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

Comments and Discussions

 
QuestionAre you a time traveller? Pin
Member 101963388-Jun-18 5:24
Member 101963388-Jun-18 5:24 
Questiontrigger Pin
Member 1377335710-Apr-18 21:21
Member 1377335710-Apr-18 21:21 
QuestionTriggers in Sql Server Pin
Member 1003591727-Mar-17 20:02
Member 1003591727-Mar-17 20:02 
AnswerRe: Triggers in Sql Server Pin
Koda Naresh27-Dec-17 22:46
Koda Naresh27-Dec-17 22:46 
QuestionCODE PROJECT TRIGGER SQL SERVER BY s.india Software Developer (Senior) Pin
mariavincentshyam13-Apr-16 21:23
mariavincentshyam13-Apr-16 21:23 
BugTypo error in What is a Trigger section Pin
Ashish Shuklaa4-Apr-16 8:16
Ashish Shuklaa4-Apr-16 8:16 
Generalthanks for sharing very informative examples Pin
saqib_amin5-Jan-16 22:54
saqib_amin5-Jan-16 22:54 
QuestionThanks plenty Pin
Member 108075601-Aug-15 7:34
Member 108075601-Aug-15 7:34 
GeneralIts really nice Article... Pin
Member 109897581-Jul-15 22:54
Member 109897581-Jul-15 22:54 
GeneralGreat Pin
Member 1162810722-Apr-15 17:15
Member 1162810722-Apr-15 17:15 
Generalthanks Pin
Iglesk17-Apr-15 19:20
Iglesk17-Apr-15 19:20 
QuestionMy vote of 1 (should really be -1 !!) Pin
Marc Scheuner17-Apr-15 2:03
professionalMarc Scheuner17-Apr-15 2:03 
AnswerRe: My vote of 1 (should really be -1 !!) Pin
Member 1102269123-Jul-16 4:44
Member 1102269123-Jul-16 4:44 
QuestionThank you. Excellent as always! Pin
Member 897912725-Feb-15 22:45
Member 897912725-Feb-15 22:45 
GeneralGreat article Pin
Member 1132366719-Feb-15 21:26
Member 1132366719-Feb-15 21:26 
QuestionTriggers Pin
Member(Jilby) 1102400716-Feb-15 20:00
Member(Jilby) 1102400716-Feb-15 20:00 
GeneralMy vote of 5 Pin
Pratik Bhuva15-Dec-14 1:53
professionalPratik Bhuva15-Dec-14 1:53 
GeneralThank you!!! Pin
RaviCG26-Nov-14 3:06
RaviCG26-Nov-14 3:06 
QuestionFor multiple rows Pin
Tripti Santikary7-Nov-14 0:44
Tripti Santikary7-Nov-14 0:44 
AnswerRe: For multiple rows Pin
satyajit mohanta18-Nov-14 1:38
satyajit mohanta18-Nov-14 1:38 
QuestionTrigger Based Pin
km@1235-Nov-14 21:30
km@1235-Nov-14 21:30 
Questionno update of trigger action tabled Pin
Member 1107716118-Sep-14 21:06
Member 1107716118-Sep-14 21:06 
QuestionGood explanation Pin
pallelokanathareddy12-Aug-14 0:07
professionalpallelokanathareddy12-Aug-14 0:07 
QuestionTriggers Pin
Member 1089876821-Jun-14 18:13
Member 1089876821-Jun-14 18:13 
GeneralMy vote of 3 Pin
Member 43966341-May-14 1:04
Member 43966341-May-14 1:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.