0% found this document useful (0 votes)
10 views34 pages

Triggers 08

A trigger is an automatic execution mechanism in a database that activates upon specific events such as insert, update, or delete actions. There are various types of triggers, including DML, DDL, and logon triggers, each serving different purposes and functionalities. The document also covers trigger syntax, examples, and best practices for managing triggers in SQL Server.

Uploaded by

Rasel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views34 pages

Triggers 08

A trigger is an automatic execution mechanism in a database that activates upon specific events such as insert, update, or delete actions. There are various types of triggers, including DML, DDL, and logon triggers, each serving different purposes and functionalities. The document also covers trigger syntax, examples, and best practices for managing triggers in SQL Server.

Uploaded by

Rasel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Triggers

Triggers
A trigger is a statement that is executed automatically by the system as a side
effect of a modification to the database.
Or

Trigger is a series of PL/SQL statements attached to a database table that


execute whenever a triggering event (select, update, insert, delete) occurs.
Or

A database trigger is a PL/SQL block that can defined to automatically


execute for insert, update, and delete statements against a table.
– The trigger can be defined to execute once for the entire statement or
once for every row that is inserted, updated, or deleted. For any one
table, there are twelve events for which you can define database
triggers.
– A database trigger can call database procedures that are also written in
PL/SQL.
To design a trigger mechanism, we must
– Specify the conditions under which the trigger is to be
executed.
– Specify the actions to be taken when the trigger executes.

Main purpose of trigger


• Main purpose is to implement the complex integrity
constraints that can’t be done with the CREATE TABLE or
ALTER TABLE command.
Trigger Types:
• Application Trigger
– Trigger will be activated if there is an event on certain
application
• Database Trigger
– Trigger will be activated if there is a data event (DML
Operation – Insert, Update, Delete) or system event
(logon or shutdown) on a schema or database

In Sql Server there are 3 types of Triggers


– DML Triggers
– DDL Triggers
– Logon Triggers
DDL triggers
• DDL triggers execute in response to a variety of data
definition language (DDL) events. These events primarily
correspond to Transact-SQL CREATE, ALTER, and DROP
statements, and certain system stored procedures that perform
DDL-like operations.
Logon triggers
• Logon triggers fire in response to the LOGON event that is
raised when a user sessions is being established.
• Triggers can be created directly from Transact-SQL statements
or from methods of assemblies that are created in the
Microsoft .NET Framework common language runtime (CLR)
and uploaded to an instance of SQL Server.
• SQL Server allows for creating multiple triggers for any
specific statement.
DML Triggers
DML Triggers: DML triggers are fired automatically in
response to DML events
or
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

DML triggers can be again classified into 2 types


• After triggers(some time called FOR triggers)
• Instead of triggers
DML Triggers Cont.
• After Triggers: After triggers fires after the triggering action.
The INSERT,UPDATE and DELETE statements, causes an
after trigger to fire after the respective statements completed.

• INSTEAD of triggers:, INSTEAD of triggers ,fires instead of


the triggering action. The INSERT, UPDATE and DELETE
statements, causes an INSTEAD of triggers to fire INSTEAD
of the respective statement execution.
Trigger Timing:
• BEFORE
where a trigger will be activated before DML process on table
occur
• AFTER
where a trigger will be activated after DML process on table
occur
• INSTEAD OF
Trigger that just functionate on VIEW and usually used to
update data on complex view
Trigger Syntex
CREATE TRIGGER triggers_name
ON table_name
FOR INSERT/DELETE
AS
BEGIN
…..
END
We will use tblEmployee and tblEmployeeAudit
tables for our examples
• tblEmployee • SQL Script to create
tblEmployeeAudit table:

CREATE TABLE tblEmployeeAudit


(
Id int identity(1,1) primary key,
AuditData nvarchar(1000)
)
AFTER TRIGGER Example
CREATE TRIGGER tr_tblEMployee_ForInsert
ON tblEmployee
FOR INSERT
AS
BEGIN
Declare @Id int
Select @Id = Id from inserted
insert into tblEmployeeAudit values('New employee with Id = ' +
Cast(@Id as nvarchar(5)) + ' is added at ' + cast(Getdate() as
nvarchar(20)))

END
In the trigger, we are getting the id from
inserted table.
• So, what is this inserted table?
• INSERTED table, is a special table used by DML triggers.
• When you add a new row into tblEmployee table, a copy of
the row will also be made into inserted table, which only a
trigger can access.
• You cannot access this table outside the context of the trigger.
The structure of the inserted table will be identical to the
structure of tblEmployee table.
• So, now if we execute the following INSERT statement on
tblEmployee. Immediately, after inserting the row into
tblEmployee table, the trigger gets fired (executed
automatically), and a row into tblEmployeeAudit, is also
inserted.

• Insert into tblEmployee values (7,'Tan', 2300, 'Female', 3)


Along, the same lines, let us now capture audit information,
when a row is deleted from the table, tblEmployee.

• Example for AFTER TRIGGER for DELETE event on


tblEmployee table:

CREATE TRIGGER tr_tblEMployee_ForDelete


ON tblEmployee
FOR DELETE
AS
BEGIN
Declare @Id int
Select @Id = Id from deleted
insert into tblEmployeeAudit values('An existing employee with Id = ' +
Cast(@Id as nvarchar(5)) + ' is deleted at ' + Cast(Getdate() as nvarchar(20)))
END
• The only difference here is that, we are specifying, the
triggering event as DELETE and retrieving the deleted row ID
from DELETED table.
• DELETED table, is a special table used by DML triggers.
• When you delete a row from tblEmployee table, a copy of the
deleted row will be made available in DELETED table, which
only a trigger can access.
• Just like INSERTED table, DELETED table cannot be
accessed, outside the context of the trigger and, the structure
of the DELETED table will be identical to the structure of
tblEmployee table.
Trigger Example of Instead of Insert
triggers:
tblEmployee tblDepartment
Trigger Example of Instead of Insert triggers:
Create the view
Create view vwEmployeeDetails
as
Select Id,name,Gender,DeptName from tbEmployee
Join Department
On Department.DeptId=tbEmployee.DepartmentId

And in this insert the value:


Insert into vwEmployeeDetails values (7,'Ali','Male','IT')
The value is not inserted because the modification affects
multiple base tables . In this problem we overcome using by
triggers, following rules is below.
vwEmployeeDetails
Trigger Example of Instead of Insert triggers:
Create trigger tr_vwEmployeeDetails_InsteadOfInsert
On vwEmployeeDetails
Instead of insert
as
begin
Select * from inserted
Select * from deleted
End

Run this code then insert the value in view. No any problem
Insert into vwEmployeeDetails values (7,'Ali','Male','IT')
• Now, let's try to insert a row into the view,
vWEmployeeDetails, by executing the following query.
• At this point, an error will be raised stating 'View or function
vWEmployeeDetails is not updatable because the modification
affects multiple base tables.'
Insert into vWEmployeeDetails values(7, 'Valarie', 'Female', 'IT')

• Triggers make use of 2 special tables, INSERTED and


DELETED.
• The inserted table contains the updated data and the deleted
table contains the old data.
• The After trigger for UPDATE event, makes use of both
inserted and deleted tables.
Create trigger tr_vWEmployeeDetails_InsteadOfInsert
on vWEmployeeDetails
Instead Of Insert
as Begin
Declare @DeptId int
--Check if there is a valid DepartmentId
--for the given DepartmentName
Select @DeptId = DeptId from tblDepartment join inserted
on inserted.DeptName = tblDepartment.DeptName
--If DepartmentId is null throw an error and stop processing
if(@DeptId is null)
Begin
Raiserror('Invalid Department Name. Statement terminated', 16, 1)
return
End
Insert into tblEmployee(Id, Name, Gender, DepartmentId)
Select Id, Name, Gender, @DeptId from inserted
End
• Raiserror ('Invalid Department Name. Statement terminated',
seriates level , State)
– Several seriates level, but 16 means user can correct query

Then insert the value that is not have in department table, in this
situation show an error

Insert into vwEmployeeDetails values (8,'Ali','Male','ITsss')

Then insert the value that is have in department table, row will be
inserted correctly
Insert into vwEmployeeDetails values (8,'Ali','Male','IT')
Trigger Example of Instead of Update triggers
Alter trigger tr_EmployeeDetails_InsteadOfUpdate1122
on vwEmployeeDetails
InsteadofUpdate
As Begin
if(Update(Gender))
begin
Update tbEmployee set Gender=inserted.Gender from inserted join
tbEmployee on tbEmployee.id=inserted.id
End
-- if name is update
if(Update(name))
Begin
Update tbEmployee set Name = inserted.name from inserted join tbEmployee
on tbEmployee.id=inserted.id
End
End Now update the view that work in both table
Update vwEmployeeDetails set DeptName='IT‘ where Id=1
Again change this query add some validation:
CREATE trigger tr_EmployeeDetails_InsteadOfUpdate11
On vwEmployeeDetails
Instead of Update
as
Begin
-- if EnployeeId is update
If (Update(Id))
Begin
Raiserror('Id cannot be changed', 16 ,1)
return
End
-- if DeptName is update
If (Update(DeptName))
Begin
Declare @DeptId int
-- Check if there is a valid DepartmentId
-- for the given Depatment Name
Select @DeptId =DeptId from Department join inserted
On inserted.DeptName = Department.DeptName
-- If DepartmentId is null throw an error
if(@DeptId is null)
begin
Raiserror ('Invalid Department Name. Statement terminated', 16 ,1)
return
End
Update tbEmployee set DepartmentId=@DeptId
From inserted join tbEmployee on tbEmployee.id=inserted.id
end
-- if Gender is update
if(Update(Gender))
begin
Update tbEmployee set Gender=inserted.Gender
From inserted join tbEmployee on tbEmployee.id=inserted.id
End
-- if name is update
if(Update(Name))
Begin
Update tbEmployee set Name=inserted.Name
From inserted join tbEmployee on tbEmployee.id=inserted.id
End
End
• Now update the view that work in both table

Update vwEmployeeDetails set DeptName='IT‘ where Id=1

Or

Update vwEmployeeDetails set Name='johny', Gender='Female',


DeptName='IT‘ where Id=1
Trigger Example of Instead of Delete triggers:
Create Trigger tr_vwEmployee_InstedOfDelete
On vwEmployeeDetails
Instead of delete
as
Begin
Delete tbEmployee from tbEmployee join deleted on
tbEmployee.Id=deleted.id
End
Again it down by subQuery:
Create Trigger tr_vwEmployee_InstedOfDelete
On vwEmployeeDetails
Instead of delete
As Begin
-- SubQuery
Delete from tbEmployee Where Id in(Select Id from deleted)
End

Now run that query and check it work or not


Delete from vwEmployeeDetails where id=3
When Not To Use Triggers:
• Triggers were used earlier for tasks such as
– maintaining summary data (e.g., total salary of each department)
– Replicating databases by recording changes to special relations (called change or delta
relations) and having a separate process that applies the changes over to a replica
• There are better ways of doing these now:
– Databases today provide built in materialized view facilities to maintain summary data
– Databases provide built-in support for replication
• Encapsulation facilities can be used instead of triggers in many cases
– Define methods to update fields
– Carry out actions as part of the update methods instead of through a trigger
• Risk of unintended execution of triggers, for example, when
– loading data from a backup copy
– replicating updates at a remote site
– Trigger execution can be disabled before such actions.
• Other risks with triggers:
– Error leading to failure of critical transactions that set off the trigger
– Cascading execution
Managing Trigger:
• Enable Trigger
– ALTER TRIGGER trigger_name ENABLE
• Disable Trigger
– ALTER TRIGGER trigger_name DISABLE
• Enable or Disable All Trigger
– ALTER TABLE table_name DISABLE | ENABLE ALL
TRIGGERS
• Delete TRIGGER
– DROP TRIGGER nama_trigger
END

You might also like