How to use Triggers in SQL Server

Introduction:

In this article i will explain what is Trigger in SQL Server.

Description:

In previous articles i explained about joinsBatches, Stored procedure, Functions, and Difference between Stored procedure and Function in SQL Server. Now i will explain what is Trigger in SQL Server.

Trigger:

A Trigger is a database object which automatically executes whenever some operation like insert, update or delete is performed on table.

Syntax:

Create Trigger <Trigger-Name> on <Table-Name>
For insert, update, delete
As
Begin

    -- Your operations here.
    print 'Done some change.'

End

Example:

Create Trigger EmpTrigger on Employee
For insert, update, delete
As
Begin

    -- Your operations here.
    print 'Done some change.'

End

Check the output of Employee table.

select * from Employee

Output:

Execute above statement, then Trigger will be created on Employee table.

Now I'm inserting one new record into Employee table.

insert into Employee(EmployeeName, Email, DepartmentID, Active)
values('Vinod Reddy', 'vinnu@studentboxoffice.in', 1, 1)

After execution above statement, EmpTrigger will be fired and the operations which are mentioned in that Trigger will be performed. It will give following message.

Done some change.

(1 row(s) affected)

Output: