A trigger is a special kind of stored procedure, that is executed automatically when a specified event fired on database server.
There are three types of triggers DML trigger, DDL trigger and Logon trigger.
1. DML trigger - A DML trigger can be created on a table or view, its executes when a user tries to update data through DML operations (insert / update / delete), trigger fires regardless of whether or not data is updated.
DML triggers have two types of nature 'After' and 'Instead of'
After - Trigger with after fires after execution of specified event for that triger is created. We use keyword FOR or AFTER for it, both are same.
Instead Of - Trigger with instead of option fires instead of executing specified event. Trigger of this nature overrides specified event or triggering statement with statements defined in body of trigger.
Instead of option can't be used with DDL or Logon triggers.
Syntax -
CREATE TRIGGER trigger_name
ON { table | view }
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS { sql_statement }
Ex. This trigger enforces a business rule when user try to insert an employee record in employee table, that protect the table from inserting bonus out of the range that company has specified.
create trigger trgEmpSalary
on tbl_employee
for Insert
AS
begin
if exists (select * from tbl_employee where bonus between 1000 and 10000)
begin
raiserror('Bonus range in company is 1000 to 10000',10,1)
rollback transaction
end
end
There are three types of triggers DML trigger, DDL trigger and Logon trigger.
1. DML trigger - A DML trigger can be created on a table or view, its executes when a user tries to update data through DML operations (insert / update / delete), trigger fires regardless of whether or not data is updated.
DML triggers have two types of nature 'After' and 'Instead of'
After - Trigger with after fires after execution of specified event for that triger is created. We use keyword FOR or AFTER for it, both are same.
Instead Of - Trigger with instead of option fires instead of executing specified event. Trigger of this nature overrides specified event or triggering statement with statements defined in body of trigger.
Instead of option can't be used with DDL or Logon triggers.
Syntax -
CREATE TRIGGER trigger_name
ON { table | view }
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS { sql_statement }
Ex. This trigger enforces a business rule when user try to insert an employee record in employee table, that protect the table from inserting bonus out of the range that company has specified.
create trigger trgEmpSalary
on tbl_employee
for Insert
AS
begin
if exists (select * from tbl_employee where bonus between 1000 and 10000)
begin
raiserror('Bonus range in company is 1000 to 10000',10,1)
rollback transaction
end
end