Click here to Skip to main content
15,867,686 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

 
GeneralMy vote of 5 Pin
HARISH SINGLA10-Apr-13 19:16
HARISH SINGLA10-Apr-13 19:16 
Questionall created triger have some miss print.. Pin
Qussar10-Apr-13 2:52
Qussar10-Apr-13 2:52 
QuestionUseful Article Pin
Member 980908522-Mar-13 2:28
Member 980908522-Mar-13 2:28 
GeneralMy vote of 5 Pin
Er. Vikas Sangal21-Mar-13 19:29
Er. Vikas Sangal21-Mar-13 19:29 
QuestionTHANKS Pin
Thillairaja21-Mar-13 2:47
Thillairaja21-Mar-13 2:47 
Questionhi Pin
Israr Zaib13-Mar-13 20:48
Israr Zaib13-Mar-13 20:48 
QuestionGood one for beginners(like me) Pin
kimberly wind7-Mar-13 19:48
kimberly wind7-Mar-13 19:48 
GeneralMy vote of 4 Pin
Member 93457483-Mar-13 20:02
Member 93457483-Mar-13 20:02 
QuestionIts Really nice one Pin
Nandakishor Arun Gaikwad1-Mar-13 20:35
Nandakishor Arun Gaikwad1-Mar-13 20:35 
GeneralMy vote of 5 Pin
Maddy selva15-Feb-13 17:41
professionalMaddy selva15-Feb-13 17:41 
SuggestionCode does not run Pin
gaurav sobti27-Jan-13 19:59
gaurav sobti27-Jan-13 19:59 
GeneralRe: Code does not run Pin
Qussar10-Apr-13 20:18
Qussar10-Apr-13 20:18 
GeneralMy vote of 5 Pin
sandeep nagabhairava24-Jan-13 20:14
sandeep nagabhairava24-Jan-13 20:14 
QuestionThank you so much Pin
qofacevic13-Jan-13 19:08
qofacevic13-Jan-13 19:08 
GeneralMy vote of 2 Pin
Member 964056230-Nov-12 2:02
Member 964056230-Nov-12 2:02 
GeneralMy vote of 2 Pin
Member 964056230-Nov-12 2:02
Member 964056230-Nov-12 2:02 
GeneralMy vote of 5 Pin
Member 964056230-Nov-12 2:02
Member 964056230-Nov-12 2:02 
GeneralMy vote of 5 Pin
Member 964056230-Nov-12 1:26
Member 964056230-Nov-12 1:26 
GeneralMy vote of 5 Pin
Ashish Rathod27-Nov-12 23:47
Ashish Rathod27-Nov-12 23:47 
QuestionTriggers Pin
mitu sinha9-Nov-12 8:16
mitu sinha9-Nov-12 8:16 
QuestionGreat Article Pin
udayakumarSubramanian23-Oct-12 5:36
udayakumarSubramanian23-Oct-12 5:36 
QuestionTamer Farouk Pin
Tamer_Farouk22-Oct-12 19:37
Tamer_Farouk22-Oct-12 19:37 
QuestionThanks Alot Pin
Member 87776479-Oct-12 20:58
Member 87776479-Oct-12 20:58 
QuestionMy query for sql Pin
sudhir kumar rathi9-Oct-12 0:26
sudhir kumar rathi9-Oct-12 0:26 
Questionple help me Pin
alirezajo0n21-Sep-12 1:24
alirezajo0n21-Sep-12 1:24 

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.