How to write Trigger in SQL Server 2005

A trigger is a special kind of stored procedure that responds to specific events. More specifically, it is attached to a Table or View or Database schemas for tracking the operations on them. The key difference between a trigger and a stored procedure is that the former is attached to a table or view and is fired only when an INSERT, UPDATE, and/or DELETE occurs, whereas a stored procedure executes at any time when it is called.

//Create Table
create table t_EmployeeInformation
employee_ID int identity(1,1) NOT NULL,
employee_Name varchar(50),
employee_EmailID varchar(20),
employee_Status varchar(10) NULL constraint
DF_t_EmployeeInformation_employee_Status default ('Active')

//Create Procedure
create procedure p_InsertEmployee
@employee_Name varchar(50),
@employee_EmailID varchar(40),
insert into t_EmployeeInformation(employee_Name,employee_EmailID)

The following code snippet shows a simple trigger which fires on an insert to table t_EmployeeInformation.

//Create Trigger
create trigger tr_InsertEmployee
on t_EmployeeInformation
after insert
declare @employee_ID int
select @employee_ID = employee_ID from inserted
update t_EmployeeInformation
set employee_Status = 'Inactive'
where employee_ID != @employee_ID

//Use Procedure to Insert Data
exec p_InsertEmployee 'khan', ''

Trigger will fire for the insert event and change all available employee_Status except the last (inserted) one.

A Rahim Khan

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: