0% found this document useful (0 votes)
45 views23 pages

Implementing Trigger: Hanoi University of Technology

Triggers are associated with tables and are invoked automatically in response to data modification statements like INSERT, UPDATE, or DELETE. They cannot be called directly and are part of a transaction. When a data modification statement occurs on a table with a trigger defined, the trigger code executes before or after the statement completes. Triggers can be used to maintain referential integrity, log audit trails, or perform calculations on modified data. Considerations for using triggers include their impact on performance and complexity they add to the database.

Uploaded by

trungt2k6
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views23 pages

Implementing Trigger: Hanoi University of Technology

Triggers are associated with tables and are invoked automatically in response to data modification statements like INSERT, UPDATE, or DELETE. They cannot be called directly and are part of a transaction. When a data modification statement occurs on a table with a trigger defined, the trigger code executes before or after the statement completes. Triggers can be used to maintain referential integrity, log audit trails, or perform calculations on modified data. Considerations for using triggers include their impact on performance and complexity they add to the database.

Uploaded by

trungt2k6
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 23

Implementing Trigger

Vu Tuyet Trinh
[email protected]
Hanoi University of Technology

1
Introduction to Triggers

 What Is a Trigger?
 Uses of Triggers
 Considerations for Using Triggers

Microsoft
What Is a Trigger?
 Associated with a Table
 Invoked Automatically
 Cannot Be Called Directly
 Is Part of a Transaction

Microsoft
Outline

 Introduction to Triggers
 Creating, Altering, and Dropping Triggers
 Working with Triggers
 Uses of Trigger
 Performance Consideration

Microsoft
Creating and Managing Triggers

 Creating Triggers
 Altering and Dropping Triggers

Microsoft
Creating Triggers
 Requires Appropriate Permissions
 Cannot Contain Certain Statements

Use
Use Northwind
Northwind
GO
GO
CREATE
CREATE TRIGGER
TRIGGER Empl_Delete
Empl_Delete ONON Employees
Employees
FOR DELETE
FOR DELETE
AS
AS
IF
IF (SELECT
(SELECT COUNT(*)
COUNT(*) FROM
FROM Deleted)
Deleted) >> 11
BEGIN
BEGIN
RAISERROR(
RAISERROR(
'You
'You cannot
cannot delete
delete more
more than
than one
one employee
employee at
at aa time.',
time.', 16,
16, 1)
1)
ROLLBACK TRANSACTION
ROLLBACK TRANSACTION
END
END

Microsoft
Altering and Dropping Triggers
 Altering a Trigger
 Changes the definition without dropping the trigger
 Can disable or enable a trigger

USE
USE Northwind
Northwind
GO
GO
ALTER
ALTER TRIGGER
TRIGGER Empl_Delete
Empl_Delete ONON Employees
Employees
FOR DELETE
FOR DELETE
AS
AS
IF
IF (SELECT
(SELECT COUNT(*)
COUNT(*) FROM
FROM Deleted)
Deleted) >> 66
BEGIN
BEGIN
RAISERROR(
RAISERROR(
 Dropping
'You
'You cannot a Trigger
cannot delete
delete more
more than
than six
six employees
employees at
at aa time.',
time.', 16,
16, 1)
1)
ROLLBACK TRANSACTION
ROLLBACK TRANSACTION
END
END

Microsoft
How Triggers Work

 How an INSERT Trigger Works


 How a DELETE Trigger Works
 How an UPDATE Trigger Works
 How an INSTEAD OF Trigger Works

Microsoft
How an INSERT Trigger Works
INSERT statement to a table with an INSERT Trigger Defined
TRIGGER Actions Execute
INSERT
INSERT [Order Details]
Trigger
[Order Details] VALUES
Code:VALUES
Trigger Code:
(10525,
(10525, 2,
2, 19.00,
USE 5,
5, 0.2)
USE Northwind
19.00, Northwind0.2)
CREATE
CREATE TRIGGER OrdDet_Insert
TRIGGER OrdDet_Insert
ON [Order Details]
ON [Order Details]
Order
FOROrder Details
Details
INSERT
FOR INSERT
OrderID
ASOrderIDProductID
AS ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
UPDATE P
UPDATE P SET SET
10522
10522 10
UnitsInStock
UnitsInStock 10 =31.00
=31.00
77
(P.UnitsInStock0.2
(P.UnitsInStock 0.2 –– I.Quantity)
I.Quantity)
10523
FROM 41
Products
10523Products
FROM 41 9.65
AS
9.65P 99
INNER
AS P INNER 0.15
JOIN
0.15 Inserted AS
JOIN Inserted AS II
ON
ON P.ProductID
P.ProductID == I.ProductID
I.ProductID
1052410524 7 7 30.00 24
30.00 240.0 0.0
Order
OrderDetails
Details 10523 2 19.00 5 0.2
Products
OrderID
OrderIDProductID
ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount Products
ProductID
ProductID UnitsInStock
UnitsInStock …… ……
10522
10522 10 10 31.00
31.00 77 0.2
0.2
10523 41 9.65 99 0.15 11 15
15
Insert
10523 statement
41 logged
9.65 0.15
10524 77 30.00 24 0.0 22 15
10
10
10524inserted
inserted 30.00 24 0.0
10523 2 19.00 5 0.2 33 65
65
10523
10523 22 19.00
19.00 55 0.2
0.2 44 20
20

Microsoft
Activating Insert Trigger

Step 1
INSERT statement to a table with an INSERT trigger
defined

Step 2
INSERT Statement Logged

Step 3
Trigger Actions Executed

Microsoft
How a DELETE Trigger Works
DELETE Statement to a table with a DELETE Trigger Defined
Trigger Actions Execute
Categories
Categories
CategoryID
CategoryID CategoryName
CategoryName Description
Description Picture
Picture
DELETE
DELETE Categories Products
Categories 11 Beverages Products
Beverages Soft
Softdrinks,
drinks,coffees…
coffees… 0x15…
0x15…
WHERE
WHERE ProductID
ProductID Discontinued
Discontinued …… ……
CategoryID 22Condiments
Condiments Sweet
Sweetandandsavory
savory… … 0x15…
0x15…
CategoryID == 44 11 00
33Confections
Confections Desserts,
Desserts, candies,
candies, …… 0x15…
0x15…
4 22
Dairy Products Cheeses
2 010 0x15…
USE Northwind
USE Northwind
CREATE 33 00
CREATE TRIGGER
TRIGGER Category_Delete
Category_Delete
ON
ON Categories
Categories 44 00
FOR
FOR DELETE
DELETE
AS
AS
UPDATE
UPDATE PP SET
SET Discontinued
Discontinued == 11
FROM
FROM Products
Products ASAS PP INNER
INNER JOIN
JOIN deleted
deleted AS
AS dd
ON P.CategoryID
ON DELETE == d.CategoryID
statement
P.CategoryID logged
d.CategoryID
Deleted
Deleted
44 Dairy
DairyProducts
Products Cheeses
Cheeses 0x15…
0x15…

Microsoft
Activating UPDATE Trigger

Step 1:
DELETE Statement to a Table with a DELETE Statement
Defined

Step 2
DELETE Statement Logged

Step 3
Trigger Actions Executed

Microsoft
How an UPDATE Trigger Works
TRIGGER Actions Execute
UPDATE Statement to a table with an UPDATE Trigger Defined
USE
USE Northwind
Northwind
GO UPDATE Employees
GO UPDATE Employees
CREATE
SET
CREATE
SET TRIGGER
TRIGGER Employee_Update
EmployeeID
EmployeeID == 17
Employee_Update
17
ON
ON Employees
Employees
WHERE
FOR WHERE EmployeeID
EmployeeID == 22
FOR UPDATE
UPDATE
AS
AS
AS Employees
Employees
IF
IF UPDATE
IF UPDATE (EmployeeID)
UPDATE (EmployeeID)
(EmployeeID) EmployeeID
BEGIN
BEGIN TRANSACTION
BEGIN TRANSACTION
TRANSACTION EmployeeID LastName
LastName FirstName
FirstName Title
Title HireDate
HireDate
RAISERROR
RAISERROR ('Transaction
('Transaction 1cannot bebe processed.\
Davolio Nancy
RAISERROR
*****
*****
('Transaction
Employee
***** Employee
Employee IDID number
ID number
cannot
cannot
1cannot
number cannot
be
Davolio
cannot bebe Nancy Sales
processed.\
processed.\
be modified.',
modified.', 10,
modified.',
Rep.
Sales10,
Rep.1)
10, 1)1)
~~~
~~~
ROLLBACK
ROLLBACK TRANSACTION
ROLLBACK TRANSACTION
TRANSACTION 22 Fuller
Barr
Barr Andrew
Andrew Vice
RR Pres. ~~~ ~~~
33 Leverling
Leverling Janet
Janet Sales
SalesRep.
Rep. ~~~
~~~
Transaction cannot be processed. 44 Peacock
Peacock Margaret
MargaretSales
SalesRep.
Rep. ~~~
~~~
***** Member number cannot be modified
Employees
UPDATE Statement loggedEmployees
as INSERT and DELETE Statements
EmployeeID
EmployeeID LastName
LastName FirstName
FirstName Title
Title HireDate
HireDate
inserted
inserted 11 Davolio
Davolio NancyNancy Sales
SalesRep.
Rep. ~~~
~~~
17
17 Fuller Andrew
Fuller 2 Andrew Vice Pres.
Vice Pres.
Fuller ~~~
Andrew~~~R Pres.
2 Barr
Barr Andrew Vice
R ~~~
~~~
deleted
deleted 33 Leverling
Leverling Janet
Janet Sales
SalesRep.
Rep. ~~~
~~~
22 Fuller 44Andrew
Fuller Peacock
Andrew Vice
VicePres.
Peacock Margaret
~~~Sales
~~~
Margaret
Pres. SalesRep.
Rep. ~~~
~~~
Microsoft
Activating DELETE Trigger

Step 1
UPDATE Statement to a Table with an UPDATE Trigger
Defined

Step 2
UPDATE Statement Logged as INSERT and DELETE
Statements

Step 3
Trigger Actions Executed

Microsoft
Outline

 Introduction to Triggers
 Creating, Altering, and Dropping Triggers
 Working with Triggers
 Uses of Trigger
 Performance Consideration

Microsoft
Uses of Triggers

 Cascade changes through related tables in


a database
 Enforce more complex data integrity than a
CHECK Constraint
 Define custom error messages
 Maintain denormalized data
 Compare before and after states of data under
modification

Microsoft
Considerations for Using Triggers
 Triggers Are Reactive; Constraints Are Proactive

 Constraints Are Checked First

 Tables Can Have Multiple Triggers for Any Action

 Table Owners Can Designate the First and Last


Trigger to Fire

 You Must Have Permission to Perform All


Statements That Define Triggers

 Table Owners Cannot Create AFTER Triggers on


Views or Temporary Tables
Microsoft
Examples of Triggers

 Enforcing Data Integrity


 Enforcing Business Rules

Microsoft
Enforcing Data Integrity
CREATE
CREATE TRIGGER
TRIGGER BackOrderList_Delete
BackOrderList_Delete
ON
ON Products FOR
Products FOR UPDATE
UPDATE
AS
AS
IF
IF (SELECT
(SELECT BO.ProductID
BO.ProductID FROM
FROM BackOrders
BackOrders ASAS BO
BO JOIN
JOIN
Inserted AS I ON BO.ProductID = I.Product_ID
Inserted AS I ON BO.ProductID = I.Product_ID
)) >> 00
BEGIN
BEGIN
DELETE
DELETE BO BO FROM
FROM BackOrders
BackOrders AS
AS BO
BO
INNER JOIN Inserted
INNER JOIN Inserted AS IAS I
ON
ON BO.ProductID
BO.ProductID == I.ProductID
I.ProductID
END
END

Products
Products BackOrders
BackOrders
ProductID
ProductID UnitsInStock
UnitsInStock …… …… ProductID
ProductID UnitsOnOrder
UnitsOnOrder ……
11 15
15 11 15
15
2 15
10 Updated
Updated 12 10
10 12 10
33 65
65 33 65
65
44 20 Trigger
TriggerDeletes
Deletes Row
Row 2 15
20

Microsoft
Enforcing Business Rules
Products with Outstanding Orders Cannot Be Deleted
IF
IF (Select
(Select Count
Count (*)
(*)
FROM
FROM [Order Details] INNER
[Order Details] INNER JOIN
JOIN deleted
deleted
ON [Order Details].ProductID = deleted.ProductID
ON [Order Details].ProductID = deleted.ProductID
)) >> 00
ROLLBACK
ROLLBACK TRANSACTION
TRANSACTION
DELETE statement executed on Trigger code Transaction
Product table checks the Order Details rolled back
table
Products
Products Order
OrderDetails
Details
ProductID
ProductID UnitsInStock
UnitsInStock …… …… OrderID
OrderIDProductID
ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
11 1515 10522
10522 10
10 31.00
31.00 77 0.2
0.2
22 010
10 10523
10523 22 19.00
19.00 99 0.15
0.15
33 6565 10524
10524 41
41 9.65
9.65 24
24 0.0
0.0
44 2020 10525
10525 77 30.00
30.00

'Transaction
'Transaction cannot
cannot bebe processed'
processed'
'This
'This product
product has
has order
order history'
history'
Microsoft
Performance Considerations

 Triggers Work Quickly Because the Inserted and


Deleted Tables Are in Cache
 Execution Time Is Determined by:
 Number of tables that are referenced
 Number of rows that are affected
 Actions Contained in Triggers Implicitly Are Part of
a Transaction

Microsoft
Summary

• Use Triggers Only When Necessary

• Keep Trigger Definition Statements as Simple as


Possible

• Include Recursion Termination Check Statements in


Recursive Trigger Definitions

• Minimize Use of ROLLBACK Statements in Triggers

Microsoft
Microsoft

You might also like