Friday, 10 October 2014

What is Trigger in SQL Server



Trigger:

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

A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server. DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view
 
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:

0 comments:

Post a Comment