You are on page 1of 27

Triggers

Presented By:Verawaty Situmorang


Trigger

 A Trigger is a block of code that constitutes a


set of T-SQL statement that are activated in
response to certain actions.
 It can also be interpreted as a kind of stored
procedure that is invoked automatically
whenever an action-such as insert, update or
delete-takes place.

11/18/21 DBS_Trigger 2
Overview of triggers
 A triggers is always defined on a table and to
be fired whenever the data in the underlying
table is affected by any of the Data
Manipulation Language (DML) – e.g.
INSERT, UPDATE, or DELETE statements.
 Trigger helps in maintaining consistency,
reliability, and correctness of the data. It
enables complex actions to be performed and
cascade the actions to other dependent
tables.

11/18/21 DBS_Trigger 3
Characteristics of trigger (1)

 It can be associated with tables.


 It cannot be defined on temporary tables or
views. However, it can reference temporary
tables.
 It is fired automatically by SQL Server
whenever any data modification is performed.
 It cannot be explicitly invoked or executed, as
in the case of stored procedure.

11/18/21 DBS_Trigger 4
Characteristics of trigger (2)

 Triggers can be nested up to 32 levels. The


nesting of triggers occurs when a trigger
performs action that initiates another trigger.
 It ensures consistent change in data.
 It cannot return data to user.

11/18/21 DBS_Trigger 5
Creating trigger
 Create
create trigger trigger_name on table_name
{[for] after | instead of} {insert, update,
delete}
as
statement_block
 Drop
drop trigger trigger_name

11/18/21 DBS_Trigger 6
Creating Trigger: trigger class types
(1)
 Trigger class:
 AFTER
After trigger is the default trigger class. This
trigger gets executed automatically after the
statement that triggered it completes. The AFTER
clause is synonym with FOR clause. You cannot
used both clause.
E.g. AFTER UPDATE or
FOR UPDATE

11/18/21 DBS_Trigger 7
Execution order after triggers

1. Declarative constraints are being checked

2. delete/insert/update is executed

3. Population of inserted and deleted

4. Execution of after trigger(s)


– But not in a predefined order!

11/18/21 DBS_Trigger 8
When is an AFTER Trigger Fired?

 An after trigger is an integral part of the


statement that fires it
 A statement is not complete until the trigger
completes!
 Execution of trigger is part of the transaction
 IF the statement is executed, then the trigger is
ALWAYS executed!
 Multiple rows insert/delete/update:
 Trigger is executed once

11/18/21 DBS_Trigger 9
Creating Trigger: trigger class types
(2)
 Trigger class:
 INSTEAD OF
Is the trigger which is executed in place of the
triggering statement. For example, a delete action
to a table containing INSTEAD OF DELETE
trigger will run the trigger rather than the delete
statement.
create trigger trigger_name on
table_name
instead of delete
as
statement_block

11/18/21 DBS_Trigger 10
Creating trigger: trigger types
 INSERT
An insert trigger is a trigger which is fired in
response to the insert-row action made in the table
where the trigger belongs.
 UPDATE
An update trigger is a trigger which is fired
whenever an attempt is made to update row(s) in
the triggered table.
 DELETE
A delete trigger is a trigger which is fired whenever
an attempt is made to delete row(s) from the
triggered table.

11/18/21 DBS_Trigger 11
Trigger restriction
 Trigger cannot be created on system table or
temporary table, although the transact-SQL
language within the trigger can reference temporary
tables or system tables.
 Only INSTEAD OF trigger can be created on VIEW
 INSTEAD OF DELETE and INSTEAD OF UPDATE
triggers cannot be defined on tables that have
corresponding ON DELETE or ON UPDATE
cascading referential integrity defined.

11/18/21 DBS_Trigger 12
Triggers
 Used for:
 Auditing

 Maintaining history tables

 Controlling denormalization

 Controlling redundancy, update of computed columns


 Enforcing referential integrity

 Enforcing complex business rules

 with control-of-flow statements


 Other automatic functionality (like sending mail, …)

 Drawbacks of triggers:
 Non standard

 Complex coding

 Enforcing integrity rules is reactive: prevention is better than

reaction

11/18/21 DBS_Trigger 13
The inserted and deleted pseudo table
 When an INSERT, UPDATE, or DELETE
trigger fired, the event creates one or more
pseudo tables (also known as logical table).
These logical tables can thought of as the
transaction logs of the event.
 There are two types of logical tables: the
INSERTED and DELETED table.
 An insert or update creates INSERTED Table
 An update or delete creates DELETED tables

11/18/21 DBS_Trigger 14
Inserted and Deleted
DML after trigger has read-access on the before and after images of
the data. Trigger can make comparisons, calculations, and (if
necessary) undo the changes (rollback).
• identical in structure to the table on which the trigger is defined
• deleted holds the before versions of the data
• inserted holds the after versions of the data

deleted.<column name> inserted. <column name>

INSERT - column value of inserted record(s)

DELETE column value of deleted record(s) -

UPDATE old column value new column value


The inserted and deleted pseudo table:
example (1)
 CREATE TRIGGER trgUpdateAuthors
ON Authors
AFTER UPDATE
AS
SELECT 'Description'='The Inserted Table'
SELECT * FROM Inserted
SELECT 'Description'='The Deleted Table'
SELECT * FROM Deleted
 Update the au_fname from Dean to Denby.

11/18/21 DBS_Trigger 16
The inserted and deleted pseudo table:
example (2)

11/18/21 DBS_Trigger 17
After Trigger Example
create trigger emp_del_trigger
on employee
after delete
as
begin
declare @rowc int
set @rowc = @@rowcount
if @rowc != 1 begin rollback tran return end

if (select emp_nr from deleted) > 200


begin
print ‘Rows for employees with an id greater’
print ‘than 200 cannot be deleted.’
rollback transaction
end
end
Why checking the number of rows affected?

11/18/21 DBS_Trigger 18
After Trigger Example
create trigger emp_upd_trigger
on employee
after update, insert
as
begin
declare @rowc int
set @rowc = @@rowcount
if @rowc != 1 begin rollback tran return end

if (select hire_date from inserted) > getdate()


begin
print ‘Hire date cannot be in the future’
rollback transaction
end
end

Why checking the number of rows affected?

11/18/21 DBS_Trigger 19
INSERT trigger: example
 create trigger trgInsertCity
on City
for insert
as
if (select count(*) from country, Inserted
where country.countryid = inserted.countryid) !=@@rowcount
/* Cancel the insert and print a message.*/
begin
rollback transaction
print 'Cannot add data, referential integrity abused
titles. No such country id in Country'
end
/* Otherwise, allow it. */
else
print 'Added!'

11/18/21 DBS_Trigger 20
Insert Trigger
 Insert-Trigger is fired once after every
INSERT:
CREATE TRIGGER trg_test_ins
ON test
AFTER INSERT
AS
BEGIN
PRINT 'Insert of 0, 1 or many records identified'
END

 Also fired once after a multiple-row insert


INSERT INTO tblTest
SELECT * FROM tblBackup

11/18/21 DBS_Trigger 21
@@ROWCOUNT
 System function @@ROWCOUNT
 Number of rows processed by immediately preceding
command
 Try:
select * from sys.objects
select @@rowcount
go
select * from sys.objects
if @@rowcount > 0
print 'Then-part: rowcount = ' + cast(@@rowcount
as varchar(10))
else
 Test for modification at the beginning of a trigger useful
print 'Else-part: rowcount = 0'
for performance reasons

11/18/21 DBS_Trigger 22
UPDATE trigger: example
 CREATE TRIGGER trgUpdateOrderID
ON Orders
FOR UPDATE
AS
IF UPDATE(OrderId)
BEGIN
RAISERROR('OrderID cannot be modified',12,2)
ROLLBACK TRAN
END

11/18/21 DBS_Trigger 23
DELETE trigger: example
USE PUBS

CREATE TRIGGER trgDeleteTitleAuthor


On Publishers
FOR DELETE
AS
Declare @RowsDeleted int
Declare @RowsLeft int
Declare @RowsLeft_char char(10)
Declare @Message char(30)
Select @RowsDeleted =(Select COUNT (*) From Deleted)
Select @RowsLeft=(Select Count(*) From Publishers)
If @RowsDeleted > 5
BEGIN
Select @RowsLEft_char= Convert(Varchar(10), @RowsLeft)
Select @message='Only '+@RowsLEft_char+' are left in publishers'
Print @message
Rollback Tran
End

11/18/21 DBS_Trigger 24
INSTEAD OF TRIGGER: example
 Use Test
create trigger trgIOD_Test1
on Test1
instead of delete
as
BEGIN
print 'you cannot delete data from table 1'
END
INSTEAD OF DELETE triggers cannot be defined on a table that has a
foreign key defined with a DELETE action.

11/18/21 DBS_Trigger 25
Altering trigger

 Altering trigger
ALTER TRIGGER trigger_name
ON table_name
[FOR] trigger_class && trigger type(s)
[WITH ENCRYPTION]
AS
sql_statement

11/18/21 DBS_Trigger 26
Trigger in MySQL
 The general syntax of CREATE TRIGGER is :
CREATE TRIGGER trigger_name
trigger_time trigger_event
ON tbl_name
FOR EACH ROW
trigger_statement

11/18/21 DBS_Trigger 27

You might also like