Вы находитесь на странице: 1из 36

Module 13:

Implementing Triggers

Vidya Vrat Agarwal. | MCT, MCSD


Overview

 Introduction to Triggers
 Defining Triggers
 How Trigger Works
 Performance Considerations
 Introduction to Triggers

Triggers are a special class of stored procedure defined


to execute / fired automatically when a DML
Statement INSERT, UPDATE or DELETE is issued
against a table or view.
Triggers are powerful tools that can be used to enforce
business rules automatically when data is modified.
Triggers can extend the integrity checking logic of SQL
Server constraints, defaults, and rules, although
constraints and defaults should be used instead
whenever they provide all the needed functionality.
1 Table can contain up to 2 Billion Triggers.
What Is a Trigger

 Associated with a Table


 Invoked Automatically
 Cannot Be Called Directly
 Is a Transaction
 Trigger can not accept parameters
Uses of Triggers

 Cascade Changes Through Related Tables in


a Database
 Enforce More Complex Data Integrity Than a
CHECK Constraint
 Define Custom Error Messages
Considerations for Using Triggers

 Triggers Are Reactive; Constraints Are Proactive


 Constraints Are Checked First
 Tables Can Have Multiple Triggers for Any Action
 Table Owners Must Have Permission
 Cannot Create Triggers on Views or Temporary Tables
 Triggers Should Not Return Result Sets
 Triggers Can Handle Multi-Row Actions
 Can be Nested up to 32 levels
Creating Triggers

 CREATE TRIGGER Statement

Create
Create Trigger
Trigger t_tdate
t_tdate
ON
ON tdate
tdate Table Name
FOR
FOR Delete
Delete
as
as
set
set nocount
nocount on on Trigger Action
delete
delete from
from tdate
tdate
begin
begin
print
print ' ' You
You can
can not
not delete
delete from
from table
table tdate'
tdate'
rollback
rollback transaction
transaction
end
end
 How Triggers Work

 How an INSERT Trigger Works


 How a DELETE Trigger Works
 How an UPDATE Trigger Works
How an INSERT Trigger Works

When an insert trigger is fired, new rows are added to


both the Trigger Table and the Inserted Table.

The Inserted Table is a logical table that holds the copy


of the rows that have been inserted.

The Inserted Table contains the logged insert activity


from the Insert Statement.
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] Code:VALUES
VALUES
Trigger Code:
INSERT
(10525,
(10525,
11 2, Statement
2, 19.00,
USE 5,
USE Northwind
19.00,
CREATE
to a Table with an INSERT
0.2)
5, 0.2)
Northwind
CREATE TRIGGER
TRIGGER OrdDet_Insert
OrdDet_Insert
Trigger Defined
ON
ON [Order
[Order
Order
Details]
Details]
Details
Order
FOR INSERT
FOR INSERT Details
OrderID
ASOrderIDProductID
AS ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
22
INSERT Statement
UPDATE
10522
P
UPDATE P SET
10522
UnitsInStock 10
10
Logged
SET
31.00
31.00 77 0.2
0.2
UnitsInStock == (P.UnitsInStock
(P.UnitsInStock –– I.Quantity)
I.Quantity)
10523
FROM
10523
FROM 41
Products
41
Products 9.65
AS
9.65
P 99
INNER
AS P INNER 0.15
JOIN
0.15
JOIN Inserted
Inserted AS
AS II
33 ON P.ProductID == I.ProductID
Order
Trigger Actions Executed I.ProductID
10524
ON 7
P.ProductID
10524 7 30.00 24
30.00 240.0 0.0
OrderDetails
Details 10523 2 19.00 5 Products
0.2
OrderID
OrderIDProductID
ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount Products
10522
ProductID UnitsInStock …
ProductID UnitsInStock ………
10522 10 10 31.00
31.00 77 0.2
0.2
10523 41 9.65 99 0.15 11 15
15
10523 statement
Insert 41 9.65
logged 0.15
10524 77 30.00 22 15
10
10
10524inserted
inserted 30.00 2424 0.0
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
How a DELETE Trigger Works

When a delete trigger is fired, deleted rows from the


affected table are placed in the Deleted Table.

The Deleted Table is a logical table that holds a copy of


the rows that have been deleted.

When a row is appended to the Deleted Table, it is no


longer exists in the database table; therefore Deleted
Table and database table have no rows in common.
How a DELETE Trigger Works
DELETE Statement to a table with a DELETE Trigger Defined
Trigger Actions Execute
Categories
Categories
11DELETE Statement
CategoryIDtoCategoryName
CategoryID a Table with a Description
CategoryName DELETE
Description Picture
Picture
DELETE Statement
DELETE CategoriesDefined
Categories 11 Beverages Products
Soft
Softdrinks,
Beverages Products drinks,coffees…
coffees… 0x15…
0x15…
WHERE ProductID Discontinued … …
Condiments ProductID Discontinued
……0x15…

WHERE 22 Condiments Sweet
CategoryID
CategoryID == 44 Sweetand
and savory
savory… 0x15…
22 33 Confections 11
Confections Desserts,
Desserts, 00
candies,
candies,…… 0x15…
0x15…
DELETE Statement
4 Logged 222
Dairy Products Cheeses 010 0x15…
USE Northwind
USE Northwind
CREATE TRIGGER Category_Delete 33 00
33
CREATE TRIGGER Category_Delete
ON Trigger Actions Executed
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
ONDELETE == d.CategoryID
statement
P.CategoryID logged
d.CategoryID
Deleted
Deleted
44 Dairy
DairyProducts
Products Cheeses
Cheeses 0x15…
0x15…
How an UPDATE Trigger Works

When an update trigger is fired on a table it take 2 steps :


1. Delete step
2. Insert Step

When an update statement is executed on a table that has


a trigger defined on it,
1. the original rows are moved into the Deleted Table
and the,
2. updated rows ( after image) are inserted into the
Inserted Table.
How an UPDATE Trigger Works
TRIGGER Actions Execute
UPDATE Statement to a table with an UPDATE Trigger Defined
USE
USE Northwind
Northwind
GO
GO UPDATE
UPDATE Employees
Employees
CREATE
SET
CREATE
ON
SET UPDATE
TRIGGER
TRIGGER
EmployeeID
Employees Statement
Employee_Update
11 EmployeeID == 17
Employee_Update
17 to a Table with an UPDATE
ON Employees
WHERE
WHERE EmployeeID
EmployeeID == 22
FOR
AS
Trigger DefinedEmployees
FOR UPDATE
UPDATE
AS
AS Employees
IF UPDATE (EmployeeID) EmployeeID
EmployeeID LastName
LastName FirstName
FirstName Title HireDate
IF
IF UPDATE
UPDATE (EmployeeID)
(EmployeeID)
BEGIN
BEGIN TRANSACTION
TRANSACTION Title HireDate
BEGIN 22 UPDATE
TRANSACTION
Statement Logged
1cannot be as
Davolio INSERT
Nancy andRep.
Nancy Sales Rep.1) ~~~
RAISERROR ('Transaction be processed.\
RAISERROR
*****
('Transaction
Employee ID number 1cannot
cannot Davolio
be
processed.\
modified.', Sales
10, ~~~
ROLLBACK
ROLLBACK
ROLLBACK DELETE Statements
***** Employee ID number2 cannot
TRANSACTION
TRANSACTION
TRANSACTION 2 Fuller
Barr
Barr
be modified.',
Andrew
Andrew Vice
10,
RR Pres. ~~~
1)
~~~
33 Leverling
Leverling Janet
Janet Sales
SalesRep.
Rep. ~~~
~~~
Transaction
Transaction cannot
cannot be processed. 44
be processed. Peacock
Peacock Margaret
MargaretSales
SalesRep.
Rep. ~~~
~~~
33 Trigger
***** Member numberActions Executed
cannot be modified
***** 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 Nancy
Nancy 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. ~~~
~~~
Data Updates on Specific Column

Create Trigger t_prod


ON prod
FOR Update
as
IF UPDATE ( product )
begin
Print ‘Column can not be Updated'
rollback transaction
end
How an INSTEAD OF Trigger Works
Create a View That Combines Two or More Tables
CREATE
CREATE VIEW
UPDATE is Made
VIEW
INSTEADAS OF Trigger Can Be on a Table or View
Customers AS
toCustomers
11 View
the
SELECT
SELECT **
FROM
FROM CustomersMex
CustomersMex Customers
INSTEAD
UNION OF
UNION Customers
SELECT ** CustomerID
CustomerIDCompanyName
CompanyName Country
Country Phone
Phone …

trigger directs
SELECT the
22 The
FROM Action ThatALFKI
CustomersGer Initiates
ALFKI the Fu…
Alfreds Trigger Does
Germany NOT Occur
030-0074321 ~~~
update to the base
FROM CustomersGer ALFKI Alfreds Fu… Germany 030-0074321 ~~~
table ANATR
ANATR Ana
AnaTrujill…
Trujill… Mexico
Mexico (5)
(5)555-4729
555-4729 ~~~
~~~
ANTON
ANTON Antonio
AntonioM…M… Mexico
Mexico (5)
(5)555-3932
555-3932 ~~~
~~~
Original Insert to
33 Allows Updates to Views Not Previously Updateable
the Customers
CustomersMex
CustomersMex
CustomerID
View Does
CustomerIDCompanyName
Not
CompanyName Country
Country Phone
CustomersGerPhone …

CustomersGer
Occur
ANATR Ana Trujill… Mexico (5) CompanyName
CustomerID 555-4729 ~~~Country Phone …
ANATR Ana Trujill… Mexico (5) CompanyName
CustomerID 555-4729 ~~~Country Phone …
ANTON
ANTON Antonio
AntonioM…
M… Mexico (5) 555-3932
Alfreds ~~~
Mexico
ALFKI AlfredsFu…
ALFKI(5) 555-3932 Germany
Fu…~~~
Germany 030-0074321
030-0074321 ~~~
~~~
CENTC Centro Co… Mexico
CENTC Centro Co… Mexico (5) 555-3392 ~~~
BLAUS(5) 555-3392
BLAUS Blauer Se…~~~
BlauerSe… Germany
Germany 0621-08460
0621-08460 ~~~
~~~
DRACD
DRACD Drachenb…
Drachenb… Germany
Germany 0241-039123
0241-039123 ~~~
~~~
Performance Considerations

 Triggers Work Quickly Because the inserted and


deleted Tables Are in Cache
 Execution Time Determined by:
 Number of tables that are referenced
 Number of rows that are affected
 Actions Contained in Triggers Implicitly Are Part of
a Transaction
Recommended Practices

Use
Use Triggers
Triggers Only
Only When
When Necessary
Necessary

Keep
Keep Definitions
Definitions as
as Simple
Simple as
as Possible
Possible

Minimize
Minimize Use
Use of
of ROLLBACK
ROLLBACK in
in Triggers
Triggers
Check Your Understanding.
Q.1 What is a Trigger.?
Q.2. Triggers are powerful tools that can be used to
enforce business rules automatically when data is
modified. ?
1. True
2. False
Q.3. A Trigger can be Associated with a Table or View.?

1. Yes
2. No
Q.4. Triggers Are Proactive ; Constraints Are Reactive.

1. True
2. False
Q.5. Name the Logical Tables that the part of SQL Server
Trigger Architecture.
Q.6. What is the role of Inserted Table when
Insert Trigger fires.
Q.7. What is the role of Deleted Table when Deleted
Trigger fires.
Q.8. How an Update Trigger use logical tables differently
than other DML Statements.
Q.9. Are there other DML Statements also which
can make a trigger to fire.

1. Yes
2. No
Q.10. A trigger can be called directly.

1. True
2. False
Q.11. You are a consultant tasked with troubleshooting a
client's database. The client has a trigger that is used
to enforce complex referential integrity. The trigger
references columns in several tables and performs a
cascading update. The client has tried several times,
but the trigger does not execute. What is the most
likely cause?

1. The trigger is not bound to a table.


2. The trigger table contains constraints that are being
violated.
3. The data is de-normalized.
4. Triggers can only reference a single table.
Q.12. Which of the following is true about triggers?

1. Trigger is never invoked automatically .


2. Triggers cannot be nested.
3. A table cannot have multiple triggers defined for it.
4. Triggers cannot be used to pass parameters.
Q.13. You are the administrator of a SQL Server database
named Purchasing. You have a DELETE trigger on the
Wishlist table that has been working for several months.
You ask one of your junior staff members to delete the
records from the Wishlist table. He reports later that he has
successfully removed the records. You check the deleted
table for the records, but they are not there. What is the
most likely explanation?

1. The deleted table is no longer in cache.


2. He used the truncate table statement.
3. The records were transferred to the transaction log.
4. The deleted table is corrupt.
Q.14. You are the administrator of a SQL Server database
named Training. You have created an INSERT trigger that
updates the Classes table when new records are added to
the Courses table. You want to verify that the trigger is
working properly and that the updated data is correct.
What should you check?
1. Application log
2. Transaction log
3. Inserted table
4. Sysobjects table
Q.15. A colleague asks you for advice. She is writing a
complex trigger that updates prices in the Sales table
based on interest rate data updated in the Statistics table.
Frequently when the trigger executes, it appears that no
changes are made at all. What could be the explanation?
1. She is using too many nested triggers.
2. SQL Server is timing out in the middle of the trigger
execution.
3. She is using the Rollback Transaction statement in her
code.
4. There is insufficient disk space to execute the trigger.
Rerview

 Introduction to Triggers
 Defining Triggers
 How Trigger Works
 Performance Considerations
Thank You.

Вам также может понравиться