Anda di halaman 1dari 15

TRIGGERS

A Trigger is T/SQL program that is automatically executed when an event


occurs, that event is being an INSERT or DELETE or UPATE on a table.
Triggers allow you to enforce referential integrity across tables in the
database. RULES enforce integrity at a column level but triggers enforce
integrity which is very complex in nature, involving multiple columns and
tables. TRIGGERS allow consistency among related tables. Since
TRIGGERS are stored in the database, all the functionalities of TSQL are
available while creating TRIGGERS.
In SQL Server 7.0 you can write as many triggers we want on the table for
the same event. ie before we can write only one insert, update and delete
trigger on a table.you can write multiple insert, update and delete
triggers.
Creating a Trigger
Triggers are created using CREATE TRIGGER statement
Syntax
CREATE TRIGGER <trigger_name>
ON <table_name>
FOR [<insert/update/delete>]
Declare
AS
Begin
sql_statements
End
Types of Triggers
1. AFTER trigger (using FOR/AFTER CLAUSE)
This trigger fires after SQL Server completes the execution of the action
successfully that fired it.
Example :If you insert record/row in a table then the trigger associated with the
insert event on this table will fire only after the row passes all the checks, such
as primary key, rules, and constraints. If the record/row insertion fails, SQL
Server will not fire the After Trigger.
2. Instead of Trigger (using INSTEAD OF CLAUSE)
This trigger fires before SQL Server starts the execution of the action
that fired it. This is much more different from the AFTER trigger, which
fires after the action that caused it to fire. We can have an INSTEAD OF
insert/update/delete trigger on a table that successfully executed but does not
include the actual insert/update/delete to the table.

Example :If you insert record/row in a table then the trigger associated with the
insert event on this table will fire before the row passes all the checks, such as
primary key, rules, and constraints. If the record/row insertion fails, SQL Server
will fire the Instead of Trigger.

Types of Triggers
In Sql Server we can create four types of triggers
Data Definition Language (DDL) triggers,
Data Manipulation Language (DML) triggers,
CLR triggers
and
Logon triggers.
1.DDL Triggers
In SQL Server we can create triggers on DDL statements (like CREATE, ALTER,
and DROP) and certain system defined stored procedures that perform DDL-like
operations.
Example : If you are going to execute the CREATE LOGIN statement or the
sp_addlogin stored procedure to create login user, then both these can
execute/fire a DDL trigger that you can create on CREATE_LOGIN event of Sql
Server.
We can use only FOR/AFTER clause in DDL triggers not INSTEAD OF
clause means we can make only After Trigger on DDL statements.
DDL trigger can be used to observe and control actions performed on the server,
and to audit these operations. DDL triggers can be used to manage
administrator tasks such as auditing and regulating database operations.
2.DML Triggers
In SQL Server we can create triggers on DML statements (like INSERT, UPDATE,
and DELETE) and stored procedures that perform DML-like operations.
DML Triggers are of two types
1.After Trigger (using FOR/AFTER CLAUSE)
This type of trigger fires after SQL Server finish the execution of the action
successfully that fired it.
Example : If you insert record/row in a table then the trigger related/associated
with the insert event on this table will fire only after the row passes all the
constraints, like as primary key constraint, and some rules. If the record/row
insertion fails, SQL Server will not fire the After Trigger.
2. Instead of Trigger (using INSTEAD OF CLAUSE)
This type of trigger fires before SQL Server starts the execution of the action that
fired it. This is differ from the AFTER trigger, which fires after the action that
caused it to fire. We can have an INSTEAD OF insert/update/delete trigger on a
table that successfully executed but does not include the actual
insert/update/delete to the table.
Example : If you insert record/row in a table then the trigger related/associated
with the insert event on this table will fire before the row passes all the
constraints, such as primary key constraint and some rules. If the record/row
insertion fails, SQL Server will fire the Instead of Trigger.

3.CLR Triggers
CLR triggers are special type of triggers that based on the CLR (Common
Language Runtime) in .net framework. CLR integration of triggers has been
introduced with SQL Server 2008 and allows for triggers to be coded in one of
.NET languages like C#, Visual Basic and F#.
We coded the objects(like trigger) in the CLR that have heavy computations or
need references to objects outside the SQL Server. We can write code for both
DDL and DML triggers, using a supported CLR language like C#, Visual basic and
F#. I will discuss CLR trigger later.
4.Logon Triggers
Logon triggers are special type of trigger that fire when LOGON event of Sql
Server is raised. This event is raised when a user session is being established
with Sql Server that is made after the authentication phase finishes, but before
the user session is actually established. Hence, all messages that we define in
the trigger such as error messages, will be redirected to the SQL Server error log.
Logon triggers do not fire if authentication fails. We can use these triggers to
audit and control server sessions, such as to track login activity or limit the
number of sessions for a specific login.
Synatx for Logon Trigger
CREATE TRIGGER trigger_name
ON ALL SERVER
[WITH ENCRYPTION]
{FOR|AFTER} LOGON
AS
sql_statement [1...n]

Syntax for Trigger


CREATE TRIGGER trigger_name
ON {table | view}
[WITH ENCRYPTION|EXECUTE AS]
{FOR|AFTER|INSTEAD OF} {[CREATE|ALTER|DROP|INSERT|UPDATE|DELETE ]}
[NOT FOR REPLICATION]
AS
sql_statement [1...n]

Trigger name
This is the name of the trigger. It should conform to the rules for identifiers in Sql
Server.
Table view
This is the table/view on which the trigger is to be created.
ENCRYPTION
This option is optional. If this option is specified, original text of the CREATE
TRIGGER statement will be encrypted.
EXECUTE AS
This option is optional. This option specifies, the security context under which
the trigger is executed.
FOR/AFTER
FOR/AFTER specifies that the trigger is After Trigger. AFTER is the default, if FOR
is the only keyword specified. AFTER triggers cannot be defined on views.
INSTEAD OF
INSTEAD OF specifies that the trigger is Instead Of Trigger.

CREATE|ALTER|DROP|INSERT|UPDATE|DELETE
These keywords specify on which action the trigger should be fired. One of these
keywords or any combination of these keywords in any order can be used.
NOT FOR REPLICATION
Indicates that the trigger should not be executed when a replication process
modifies the table involved in the trigger.
AS
After this we specifies the actions and condition that the trigger perform.
sql_statement
These are the trigger conditions and actions.
The trigger actions specified in the T-SQL statements.
**********************************

There are three type of Triggers


1)DML Trigger:
a)Instead of Trigger:
Instead of trigger are fired in place of the triggering action
such as an insert,update, or delete
b)After Trigger:
After trigger excute following the triggering action ,such as
an insert,update,or delete.
2)DDL Trigger:
This type of trigger is fired against DDL statements like Drop
Table,Create Table,Or Alter Table,DDL Triggers are always
after Triggres
3)Logon trigger:
This type of trigger is fired against a LOGON event before a
user session is established to the SQL Server

Uses of Triggers
Triggers can enforce referential integrity that is consistency of database
values across multiple tables.
Triggers can help you keep derived data in tables or derived data current.
Update to a table can be controlled based on values prior to and after
update.
TO solve complex business problems
Triggers can be used to audit the information about who created this
record, when it got updated and who did that etc.
Magic Tables

Inside a trigger program (T/SQL block of code) we can access two magic
tables called INSERTED and DELETED.
The INSERTED, DELETED tables essentially the image of original rows
that caused the trigger to fire.
These values are available for access only inside the trigger.
The INSERTED table contains rows that are being inserted
The DELETED table contains the rows that are being deleted.
Update Statements are treated as DELETED and INSERTED.
The rows prior to update are place in the DELETE table and rows after
update are placed in the INSERTED table.
The IF UPDATE statement allows you to check if a particular column has
been modified. This statement returns TRUE if a specific column in a row
has been modified.
Syntax
if UPDATE (<col_name>)
------Example
CREATE TRIGGER tr_insert ON mf_download
FOR INSERT
AS
if exists (select book_id from books,inserted where id = inserted.id) then
begin
update book
set book_nm = inserted.book_nm,
updt_date = getdate()
from book, inserted
where book.book_id = inserted.book_id
end0
else
begin
insert into book (book_id, book_nm, book_desc, book_author, crt_dt)
select book_id, book_nm, book_desc, book_author, getdate() from inserted
end
Information on Triggers
About triggers you can get the information using sp_help <trigger name>
which shows the owner and type of the trigger.
Syntax
sp_help <trigger_name>
Example
tr_insert_emp
----------------------------------If you want to see the text of any trigger then use sp_helptext system
stored procedure

Syntax
sp_helptext <trigger_name>
Example
sp_helptext tr_insert_emp
------------------------------------sp_depends system stored procedure on a trigger displays all the
database objects referenced by a trigger.
Syntax
sp_depends <trigger_name>
Example
sp_depends tr_insert_emp
Dropping a Trigger.
Triggers can be dropped using drop trigger command
Syntax
Drop trigger <trigger_name>
Example
Drop trigger tr_insert_emp.
When you drop a table all the associated triggers will get dropped automatically.

Rules for Triggers


Triggers are automatically invoked based on the specified events on table.
You cannot execute a trigger.
Triggers cannot send and receive parameters.
Only three kinds of triggers (insert, update, delete) are allowed on a table.
The TRUNCATE function does not cause the TRIGGER to fire since it is non-logged
function.

Examples: AFTER trigger (using FOR/AFTER CLAUSE)


First create table Employee_Demo
CREATE TABLE Employee_Demo
(
Emp_ID int identity,
Emp_Name varchar(55),
Emp_Sal decimal (10,2)
)
-- Now Insert records
Insert into Employee_Demo values ('Amit',1000)

Insert
Insert
Insert
Insert

into
into
into
into

Employee_Demo
Employee_Demo
Employee_Demo
Employee_Demo

values
values
values
values

('Mohan',1200)
('Avin',1100)
('Manoj',1300)
('Riyaz',1400)

Now create table Employee_Demo_Audit for logging/backup purpose of


table Employee_Demo
create table Employee_Demo_Audit
(
Emp_ID int,
Emp_Name varchar(55),
Emp_Sal decimal(10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
Now I am going to explain the use of After Trigger using Insert, Update, Delete
statement with example

After Insert Trigger


-- Create trigger on table Employee_Demo for Insert statement
CREATE TRIGGER trgAfterInsert on Employee_Demo
FOR INSERT
AS
declare @empid int, @empname varchar(55), @empsal decimal(10,2),
@audit_action varchar(100);
select @empid=i.Emp_ID from inserted i;
select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
set @audit_action='Inserted Record -- After Insert Trigger.'; insert into
Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Tim
estamp)
values (@empid,@empname,@empsal,@audit_action,getdate());
PRINT 'AFTER INSERT trigger fired.'
--Output will be

--Now try to insert data in Employee_Demo table


insert into Employee_Demo(Emp_Name,Emp_Sal)values ('Shailu',1000);
--Output will be

--now select data from both the tables to see trigger action

select * from Employee_Demo


select * from Employee_Demo_Audit
--Output will be

Triggers have inserted the new record to Employee_Demo_Audit table for insert
statement. In this way we can trace a insert activity on a table using trigger.

After Update Trigger


-- Create trigger on table Employee_Demo for Update statement
CREATE TRIGGER trgAfterUpdate ON dbo.Employee_Demo
FOR UPDATE
AS
declare @empid int, @empname varchar(55), @empsal decimal(10,2),
@audit_action varchar(100);
select @empid=i.Emp_ID from inserted i;
select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i; if update(Emp_Name)
set @audit_action='Update Record --- After Update Trigger.';
if update (Emp_Sal)
set @audit_action='Update Record --- After Update Trigger.';
insert
intoEmployee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_
Timestamp)
values (@empid,@empname,@empsal,@audit_action,getdate());
PRINT 'AFTER UPDATE trigger fired.'
--Output will be

--Now try to upadte data in Employee_Demo table


update Employee_Demo set Emp_Name='Pawan' Where Emp_ID =6;
--Output will be

--now select data from both the tables to see trigger action
select * from Employee_Demo
select * from Employee_Demo_Audit
--Output will be

Triggers have inserted the new record to Employee_Demo_Audit table for update
statement. In this way we can trace a update activity on a table using trigger.
After Delete Trigger
-- Create trigger on table Employee_Demo for Delete statement
CREATE TRIGGER trgAfterDelete ON dbo.Employee_Demo
FOR DELETE
AS
declare @empid int, @empname varchar(55), @empsal decimal(10,2),
@audit_action varchar(100); select @empid=d.Emp_ID FROM deleted d;
select @empname=d.Emp_Name from deleted d;
select @empsal=d.Emp_Sal from deleted d;
select @audit_action='Deleted -- After Delete Trigger.';
insert into Employee_Demo_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values (@empid,@empname,@empsal,@audit_action,getdate());
PRINT 'AFTER DELETE TRIGGER fired.'
--Output will be

--Now try to delete data in Employee_Demo table


DELETE FROM Employee_Demo where emp_id = 5
--Output will be

--now select data from both the tables to see trigger action
select * from Employee_Demo
select * from Employee_Demo_Audit
--Output will be

Triggers have inserted the new record to Employee_Demo_Audit table for delete
statement. In this way we can trace a delete activity on a table using trigger.

Examples: Instead of Trigger (using INSTEAD OF CLAUSE)


Now I am going to explain the use of Instead of Trigger using Insert, Update,
Delete statement with example

Instead of Insert Trigger


-- Create trigger on table Employee_Demo for Insert statement
CREATE TRIGGER trgInsteadOfInsert ON dbo.Employee_Demo
INSTEAD OF Insert
AS
declare @emp_id int, @emp_name varchar(55), @emp_sal decimal(10,2),
@audit_action varchar(100);
select @emp_id=i.Emp_ID from inserted i;
select @emp_name=i.Emp_Name from inserted i;
select @emp_sal=i.Emp_Sal from inserted i;
SET @audit_action='Inserted Record -- Instead Of Insert Trigger.';
BEGIN
BEGIN TRAN
SET NOCOUNT ON
if(@emp_sal>=1000)
begin
RAISERROR('Cannot Insert where salary < 1000',16,1); ROLLBACK; end
else begin Insert into Employee_Demo (Emp_Name,Emp_Sal) values
(@emp_name,@emp_sal); Insert into
Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Tim
estamp)
values(@@identity,@emp_name,@emp_sal,@audit_action,getdate());
COMMIT;
PRINT 'Record Inserted -- Instead Of Insert Trigger.'
END
--Output will be

--Now try to insert data in Employee_Demo table


insert into Employee_Demo values ('Shailu',1300)
insert into Employee_Demo values ('Shailu',900) -- It will raise error since
we are checking salary >=1000
--Outputs will be

--now select data from both the tables to see trigger action
select * from Employee_Demo
select * from Employee_Demo_Audit
--Output will be

Trigger have inserted the new record to Employee_Demo_Audit table for insert
statement. In this way we can apply business validation on the data to be
inserted using Instead of trigger and can also trace a insert activity on a table.
Instead of Update Trigger
-- Create trigger on table Employee_Demo for Update statement
CREATE TRIGGER trgInsteadOfUpdate ON dbo.Employee_Demo
INSTEAD OF Update
AS
declare @emp_id int, @emp_name varchar(55), @emp_sal decimal(10,2),
@audit_action varchar(100);
select @emp_id=i.Emp_ID from inserted i;
select @emp_name=i.Emp_Name from inserted i;

select @emp_sal=i.Emp_Sal from inserted i;


BEGIN
BEGIN TRAN
if(@emp_sal>=1000)
begin
RAISERROR('Cannot Insert where salary < 1000',16,1); ROLLBACK; end
else begin
insert into
Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Tim
estamp) values(@emp_id,@emp_name,@emp_sal,@audit_action,getdate());
COMMIT;
PRINT 'Record Updated -- Instead Of Update Trigger.'; END
--Output will be

--Now try to upadte data in Employee_Demo table


update Employee_Demo set Emp_Sal = '1400' where emp_id = 6
update Employee_Demo set Emp_Sal = '900' where emp_id = 6
--Output will be

--now select data from both the tables to see trigger action
select * from Employee_Demo
select * from Employee_Demo_Audit
--Output will be

Trigger have inserted the updated record to Employee_Demo_Audit table for


update statement. In this way we can apply business validation on the data to be
updated using Instead of trigger and can also trace a update activity on a table.

Instead of Delete Trigger


-- Create trigger on table Employee_Demo for Delete statement
CREATE TRIGGER trgAfterDelete ON dbo.Employee_Demo
INSTEAD OF DELETE
AS
declare @empid int, @empname varchar(55), @empsal decimal(10,2),
@audit_action varchar(100); select @empid=d.Emp_ID FROM deleted d;
select @empname=d.Emp_Name from deleted d;
select @empsal=d.Emp_Sal from deleted d;
BEGIN TRAN if(@empsal>1200) begin
RAISERROR('Cannot delete where salary > 1200',16,1);
ROLLBACK;
end
else begin
delete from Employee_Demo where Emp_ID=@empid;
COMMIT;
insert into
Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Tim
estamp)
values(@empid,@empname,@empsal,'Deleted -- Instead Of Delete
Trigger.',getdate());
PRINT 'Record Deleted -- Instead Of Delete Trigger.' end END
--Output will be

--Now try to delete data in Employee_Demo table

DELETE FROM Employee_Demo where emp_id = 1


DELETE FROM Employee_Demo where emp_id =3
--Output will be

--now select data from both the tables to see trigger action
select * from Employee_Demo
select * from Employee_Demo_Audit
--Output will be

Triggers have inserted the deleted record to Employee_Demo_Audit table for


delete statement. In this way we can apply business validation on the data to be
deleted using Instead of trigger and can also trace a delete activity on a table.

Anda mungkin juga menyukai