Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views36 pages

Triggers

The document provides an overview of database triggers, which are automatic actions executed in response to specific events such as data manipulation (DML) and data definition (DDL) operations. It details the types of triggers, including DML triggers (AFTER and INSTEAD OF), their syntax, and the use of INSERTED and DELETED tables for tracking changes. Additionally, it discusses the advantages and disadvantages of triggers, along with examples and alternatives for enforcing data integrity.

Uploaded by

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

Triggers

The document provides an overview of database triggers, which are automatic actions executed in response to specific events such as data manipulation (DML) and data definition (DDL) operations. It details the types of triggers, including DML triggers (AFTER and INSTEAD OF), their syntax, and the use of INSERTED and DELETED tables for tracking changes. Additionally, it discusses the advantages and disadvantages of triggers, along with examples and alternatives for enforcing data integrity.

Uploaded by

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

Triggers

Database Programming
Overview
 A trigger automatically executes when a particular
EVENT occurs in the database
 Different types of Triggers exist
 DML triggers
 DDL triggers
 DATABASE triggers
 ( LOGON / LOGOFF / STARTUP / SHUTDOWN )

 Basic difference in these triggers


 The ACTION (event) that fires them
 Other differences also exist

2
Types of Triggers
 DML triggers execute when a user tries to modify data
through a data manipulation language (DML) event
 INSERT, UPDATE, or DELETE statements
 DDL triggers will be fired in response to different Data
Definition Language (DDL) events
 CREATE, ALTER, DROP, GRANT, DENY, and REVOKE
statements.
 Logon triggers executes in response to a LOGON
event
 Fired when a user session is established
 Logon triggers fire after the authentication phase of logging in
finishes, but before the user session is actually established.

3
DML Triggers
 Triggers can include any number and kind of Transact-
SQL statements
 If you want to execute logic before or after the Insert,
Update, or Delete in a table then use Triggers.
 DML triggers are frequently used for enforcing business
rules that can not be enforced by Declarative Referential
Integrity (DRI)
 Referential integrity refers to the rules about the relationships
between the primary and foreign keys of tables
 DML triggers can be used
 To enforce rules that cannot be done via other constraints
 to enforce cross-database referential integrity

4
DML Triggers (cont.)
 Triggers can evaluate data before it has been committed
to the database.
 Triggers can perform the following actions before or after
the DML statement takes place
 Compare before and after versions of data
 Rollback invalid modification
 Read and Modify data from other tables
 Even from tables in another database
 Execute stored procedures

5
Type of DML Triggers
 2 types of DML Triggers exist in SQL Server
 AFTER TRIGGERS and INSTEAD OF TRIGGERS

 AFTER Trigger is executed only after the triggering SQL


statement has executed successfully
 Successful execution includes all referential cascade actions
and constraint checks
 INSTEAD OF Trigger is defined on a table to replace the
action of the triggering SQL statement
 Any Trigger and the DML statement that invoked it are
assumed to be in the same TRANSACTION

6
Triggers - Review
 What is a Trigger?
 What type of Trigger are there?
 When is a DML Trigger executed?
 What is the difference between an AFTER Trigger and
an INSTEAD OF Trigger?

NEXT
 Creating Triggers

7
CREATE TRIGGER Syntax
CREATE TRIGGER trigger_name
ON tableName
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS
BEGIN
sql_statements
END

8
CREATE TRIGGER Syntax (cont.)
 FOR | AFTER
 Defines an AFTER DML trigger
 The trigger is fired only when all operations specified in the
triggering SQL statement have executed successfully.
 AFTER is the default when FOR is the only keyword specified

 INSTEAD OF
 Defines an INSTEAD OF trigger
 Fired instead of the triggering SQL statement
 Overrides the actions of the triggering statements

9
CREATE TRIGGER Syntax (cont.)
 { [ DELETE ] [ , ] [ INSERT ] [ , ] [ UPDATE ] }

 Specifies the statements that activates the DML trigger


 At least one of theses options must be specified
 Any combination of these options (in any order) is allowed in the
trigger definition
 Only one INSTEAD OF trigger can be defined for each action
(INSERT, UPDATE, or DELETE statement)

10
The Inserted and Deleted Tables
 DML triggers use the INSERTED and DELETED logical
(conceptual) tables
 These tables are structurally similar to the trigger-Table
 The Deleted Table holds the old values of the rows
before they are changed or deleted
 The Inserted Table holds the new values of the rows
after they are inserted or changed

 In the case of UPDATE statements, both the Deleted


Table and Inserted Table will contain rows

11
Deleted and Inserted Tables (cont.)
After Triggers
Table1
Col1 Col2 Col3
Action

Action Completed?

Fire Trigger

12
Deleted and Inserted Tables (cont.)
 AFTER INSERT Trigger
Table1 DELETED Table
Col1 Col2 Col3 Col1 Col2 Col3
A B 2
D G 109
X L 67

INSERTED Table
Col1 Col2 Col3
X L 67

13
Deleted and Inserted Tables (cont.)
 AFTER DELETE Trigger
Table1 DELETED Table
Col1 Col2 Col3 Col1 Col2 Col3
A B 2 D G 109
D G 109

INSERTED Table
Col1 Col2 Col3

14
Deleted and Inserted Tables (cont.)
 AFTER UPDATE Trigger
Table1 DELETED Table
Col1 Col2 Col3 Col1 Col2 Col3
A B 2 D G 109
D GG 109

INSERTED Table
Col1 Col2 Col3
D GG 109

15
Deleted and Inserted Tables (cont.)
 AFTER INSERT Trigger
TableA INDERTED DELETED
Col1 Col2 Col3 Col1 Col2 Col3 Col1 Col2 Col3
AL KM 123
XE BT 786

INSERT TableA (Col1, Col2, Col3)


VALUES (‘AP’, ‘KX’, 399)

TableA INDERTED DELETED


Col1 Col2 Col3 Col1 Col2 Col3 Col1 Col2 Col3
AL KM 123 AP KX 399
XE BT 786
AP KX 399

16
Deleted and Inserted Tables (cont.)
 AFTER DELETE Trigger
TableA INDERTED DELETED
Col1 Col2 Col3 Col1 Col2 Col3 Col1 Col2 Col3
AL KM 123
XE BT 786

DELETE TableA
WHERE COL1 = ‘XE’

TableA INDERTED DELETED


Col1 Col2 Col3 Col1 Col2 Col3 Col1 Col2 Col3
AL KM 123 XE BT 786

17
Deleted and Inserted Tables (cont.)
 AFTER UPDATE Trigger
TableA INDERTED DELETED
Col1 Col2 Col3 Col1 Col2 Col3 Col1 Col2 Col3
AL KM 123
XE BT 786

UPDATE TableA
SET Col1 = ‘XX’
WHERE Col1 = ‘AL’

TableA INDERTED DELETED


Col1 Col2 Col3 Col1 Col2 Col3 Col1 Col2 Col3
AL KM 123 XX KM 123 AL KM 123
XE BT 786
18
Triggers - Review
 What is a Trigger?
 What type of Trigger are there?
 When is a DML Trigger executed?

 What is the difference between an AFTER Trigger and


an INSTEAD OF Trigger?

 CREATE TRIGGER statement (syntax)

 The Inserted Table and Deleted Table

19
Example
 Create a Trigger that will restrict the INSERT operation
on the Employee table.

CREATE TRIGGER trgDenyInsertEmployee


ON Employee
FOR INSERT
AS
BEGIN
PRINT 'YOU CANNOT PERFORM INSERT OPERATION'
ROLLBACK TRANSACTION
END

??? When will this trigger det fired ???

20
Example
 Write a message to the AlertQueue table whenever
someone tries to insert more than ONE record in the
Customer table
CREATE TRIGGER trgWriteToAlertQueue
ON Customer
AFTER INSERT
AS
BEGIN
IF ( SELECT COUNT(*) FROM INSERTED ) > 1
ROLLBACK TRANSACTION

DECLARE @FullName varchar(100), @Email varchar(5)

SELECT @FullName = FName + ‘ ‘ + LName, @email = Email


FROM INSERTED

INSERT INTO AlertQueue ( GetDate(),@FullName, @email )


21
END
Example
CREATE TRIGGER trgTblEmployeeIns ON tblEmployee
FOR INSERT
AS
BEGIN
INSERT Audit
( LoginID , DateTime , Action , TableName , PrimaryKey )
SELECT
SYSTEM_USER , GetDate(), ‘I’ , ‘tblEmployee’ , EmployeeID
FROM Inserted

END

22
INSTEAD OF TRIGGERS
 INSTEAD OF TRIGGERS is defined on a table to
replace the action of the triggering SQL statement
 INSTEAD OF DELETE and INSTEAD OF UPDATE
triggers cannot be defined on a table that has a foreign
key that is defined by using a DELETE or UPDATE
cascading action

 Typically, the INSTEAD OF trigger is defined on a view


to modify data in one or more base tables

23
Example – Views for Updates
 Creating a View
CREATE VIEW vwEmployeeDetail
AS
SELECT E.EmpID, E. Name, E.Gender, D.DeptName
FROM Employee E JOIN Department D
ON E.DepID = D.DepID

 Testing the View (Exercise)


UPDATE vwEmployeeDetail
SET DeptName = ‘IT’
WHERE EmpID = 2

UPDATE vwEmployeeDetail (ERROR)


SET Name = ‘Samson’ , DeptName = ‘IT’
24
WHERE EmpID = 2
Example
 Testing the INSERTED and DELETED tables with a
INSTEAD OF TRIGGER
 Question:
 What will be displayed when the following trigger is fired?

CREATE TRIGGER trigTest


ON EmpDetails
INSTEAD OF INSERT
AS
BEGIN
SELECT * FROM DELETED
SELECT * FROM INSERTED
END
25
Example
 INSTEAD OF DELETE TRIGGER - Mark a record as
logically deleted instead of a delete action

CREATE TRIGGER trigDeleteEmployee ON Employee


INSTEAD OF DELETE
AS
BEGIN
UPDATE Employee
SET Employee.Status = ‘DELETED’
WHERE Employee.ID = DELETED.ID
END

26
Using Triggers - Tips
 Write all your triggers with the assumption that more
than 1 row will be affected
 The trigger has the capability to roll back its actions as
well as the actions of the modification statement that
invoked it
 Note: The INSTEAD OF trigger in fired instead of the
triggering action
 the triggering action id cancelled
 We can define an INSTEAD OF trigger on a view (but
not AFTER triggers)

27
Example 1
 Insert a message into the MESSAGE table whenever a
new customer is registered.
CREATE TRIGGER trgInsertMessage
ON Customer
AFTER INSERT
AS
BEGIN
INSERT Message (Msg, CustID)
SELECT 'Sussessful Registration', I.CustID
FROM Inserted I
END
GO

INSERT Customer ( CustomerName, email )


VALUES ('Solomon', '[email protected]’)
, ('Martha', '[email protected]’)
, ('Genet', 'fff@gmail')
28
UPDATE on a Specific Column
 Trigger can perform certain actions based on UPDATE
to specific columns
 Use UPDATE() in the body of the trigger for this purpose
 UPDATE() tests for an UPDATE attempt on one column

 UPDATE ( column )
 Returns a Boolean value that indicates whether an UPDATE
attempt was made on a specified column of a table or view.
 Can be used anywhere inside the body of UPDATE trigger to
test whether the trigger should execute certain actions
 Example
IF(UPDATE(CustID))
BEGIN
.. .. .. …
END
29
Example 2
 Update of multiple records
CREATE TRIGGER trgUpdateLog
ON Customer
AFTER UPDATE
AS
BEGIN
IF ( UPDATE(CustID) )
BEGIN
RAISERROR('ID cannot be changed', 16,1)
RETURN
END

IF(UPDATE(CusType))
BEGIN
INSERT LogTable (CustID, Details)
SELECT I.CustID, I.CustomerName + I.CusType
FROM inserted I
END
.- - - -
30
END
Example 2 (cont.)
 Test the Trigger

UPDATE Customer
SET CusType = 'F'
WHERE CusType = 'C’

GO

UPDATE Customer
SET CustID = 4
WHERE CusType = 'C'

31
Example 3
 Write to Audit table if colA is changed
CREATE trigger trgCustomerUpd on Customer FOR UPDATE
AS
BEGIN
INSERT Audit (LoginID, DateTime, Action, TableName, PrimaryKey
, ColumnName, NewValue, OldValue)

SELECT SYSTEM_USER, GetDate(), 'U', ‘Customer', i.CustomerID


, ‘ColA', CONVERT(varchar(3000), i. ColA), CONVERT(varchar(3000), d. ColA)

FROM INSERTED I inner join DELETED d ON i.CustomerID = d.CustomerID


WHERE ( i. ColA is not NULL and d. ColA is NULL )
or (i. ColA is NULL and d. ColA is not NULL )
or i. ColA <> d. ColA
END

32
Triggers - Disadvantages
 Triggers increase the complexity of the database
 If the trigger is badly designed or overused
 it will lead to major performance issues due to executing it each
time a DML action is performed
 It is not easy to view and trace DML database triggers
 it as it is invisible to developers and the applications
 Triggers execute invisible to client-application
application.
 It is easy to forget about triggers and if there is no documentation
 Triggers run every time when the database fields are
updated and it is overhead on system
 It makes system run slower.

33
Trigger Alternatives
 Integrity constraints should be enforced at the lowest
level by using the PRIMARY KEY and UNIQUE
constraints rather than using the triggers
 Domain integrity should be enforced through CHECK
constraints
 Referential integrity should be enforced through the
FOREIGN KEY constraints

 Use the DML triggers only if the features supported by a


specific constraint cannot meet your application
requirements

34
Disabling Triggers
 We can disable a trigger temporarily by using the
DISABLE TRIGGER statement

DISABLE TRIGGER sales.trgMembersInsert


ON sales.members

 Disable all trigger on a table


 To disable all triggers on a table, you use:

DISABLE TRIGGER ALL ON table_name

35
Help on Triggers
 Getting Information About DML Triggers

SELECT * from sys.trigger_events


SELECT * from sys.triggers

EXEC sp_helptext 'triggerName';

36

You might also like