SQL Server: Triggers

 SQL Server     sbo     Updated on Dec 22, 2013     VIKRAM     878   

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:

 

  Related Articles
SQL Server: Difference between Stored Procedure and Function
SQL Server: Functions
SQL Server: Named Batches
SQL Server: Anonymous Batches
SQL Server: Batches
  Recent Articles
SQL Server: Difference between Stored Procedure and Function
SQL Server: Functions
SQL Server: Named Batches
SQL Server: Anonymous Batches
SQL Server: Batches