Upload
sathish-kumar-r
View
222
Download
0
Embed Size (px)
Citation preview
8/9/2019 Module 13 Implementing Triggers
1/36
Module 13:Implementing Triggers
Vidya Vrat Agarwal. | MCT, MCSD
8/9/2019 Module 13 Implementing Triggers
2/36
Overview
Introduction to Triggers
Defining Triggers
How Trigger Works
Performance Considerations
8/9/2019 Module 13 Implementing Triggers
3/36
Introduction to Triggers
Triggers are a special class ofstored procedure definedto execute / fired automatically when a DMLStatement INSERT, UPDATE or DELETE is issuedagainst a table or view.
Triggers are powerful tools that can be used to enforcebusiness rules automatically when data is modified.
Triggers can extend the integrity checking logic of SQLServer constraints, defaults, and rules, althoughconstraints and defaults should be used instead
whenever they provide all the needed functionality.
1 Table can contain up to 2 Billion Triggers.
8/9/2019 Module 13 Implementing Triggers
4/36
What Is a Trigger
Associated with a Table
Invoked Automatically
Cannot Be Called Directly
Is a Transaction
Trigger can not accept parameters
8/9/2019 Module 13 Implementing Triggers
5/36
Uses of Triggers
Cascade Changes Through Related Tables ina Database
Enforce More Complex Data Integrity Than aCHECK Constraint
Define Custom Error Messages
8/9/2019 Module 13 Implementing Triggers
6/36
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
8/9/2019 Module 13 Implementing Triggers
7/36
Creating Triggers
CREATE TRIGGER Statement
Create Trigger t_tdate
ON tdate
FOR Deleteas
set nocount on
delete from tdate
begin
print ' You can not delete from table tdate'
rollback transaction
end
Create Trigger t_tdate
ON tdate
FOR Deleteas
set nocount on
delete from tdate
begin
print ' You can not delete from table tdate'rollback transaction
end
Table Name
Trigger Action
8/9/2019 Module 13 Implementing Triggers
8/36
How Triggers Work
How an INSERT Trigger Works
How a DELETE Trigger Works
How an UPDATE Trigger Works
8/9/2019 Module 13 Implementing Triggers
9/36
How an INSERT Trigger Works
When an insert trigger is fired, new rows are added toboth the Trigger Table and the Inserted Table.
The Inserted Table is a logical table that holds the copyof the rows that have been inserted.
The Inserted Table contains the logged insert activity
from the Insert Statement.
8/9/2019 Module 13 Implementing Triggers
10/36
How an INSERT Trigger Works
INSERT statement to a table with an INSERT Trigger DefinedINSERT [Order Details] VALUES
(10525, 2, 19.00, 5, 0.2)
INSERT [Order Details] VALUES
(10525, 2, 19.00, 5, 0.2)
Order DetailsOrder DetailsOrder Details
OrderIDOrderID
10522
10523
10524
10522
10523
10524
ProductIDProductID
10
41
7
10
41
7
UnitPriceUnitPrice
31.00
9.65
30.00
31.00
9.65
30.00
QuantityQuantity
7
9
24
7
9
24
DiscountDiscount
0.2
0.15
0.0
0.2
0.15
0.0
519.002 0.210523
Insert statement logged
insertedinsertedinserted
1052310523 22 19.0019.00 55 0.20.2
TRIGGER Actions Execute
Order DetailsOrder DetailsOrder Details
OrderIDOrderID
10522
10523
10524
10522
10523
10524
ProductIDProductID
10
41
7
10
41
7
UnitPriceUnitPrice
31.00
9.65
30.00
31.00
9.65
30.00
QuantityQuantity
7
9
24
7
9
24
DiscountDiscount
0.2
0.15
0.0
0.2
0.15
0.0
519.002 0.210523
Trigger Code:
USE Northwind
CREATE TRIGGER OrdDet_Insert
ON [Order Details]
FOR INSERT
AS
UPDATE P SETUnitsInStock = (P.UnitsInStock I.Quantity)
FROM Products AS P INNER JOIN Inserted AS I
ON P.ProductID = I.ProductID
Trigger Code:
USE Northwind
CREATE TRIGGER OrdDet_Insert
ON [Order Details]
FOR INSERT
AS
UPDATE P SETUnitsInStock = (P.UnitsInStock I.Quantity)
FROM Products AS P INNER JOIN Inserted AS I
ON P.ProductID = I.ProductID
UPDATE P SETUnitsInStock = (P.UnitsInStock I.Quantity)
FROM Products AS P INNER JOIN Inserted AS I
ON P.ProductID = I.ProductID
ProductsProductsProducts
ProductIDProductID UnitsInStockUnitsInStock
1
2
3
4
12
3
4
15
10
65
20
1510
65
20
2 15
INSERT Statement to a Table with an INSERT
Trigger Defined
INSERT Statement Logged
Trigger Actions Executed
111
222
333
8/9/2019 Module 13 Implementing Triggers
11/36
How a DELETE Trigger Works
When a delete trigger is fired, deleted rows from theaffected table are placed in the Deleted Table.
The Deleted Table is a logical table that holds a copy ofthe rows that have been deleted.
When a row is appended to the Deleted Table, it is nolonger exists in the database table; therefore Deleted
Table and database table have no rows in common.
8/9/2019 Module 13 Implementing Triggers
12/36
How a DELETE Trigger Works
DELETE Statement to a table with a DELETE Trigger DefinedDELETE Statement to a table with a DELETE Trigger Defined
DeletedDeletedDeleted
44 Dairy ProductsDairy Products CheesesCheeses 0x150x15
DELETE statement logged
CategoriesCategoriesCategories
CategoryIDCategoryID
1
2
3
1
2
3
CategoryNameCategoryName
Beverages
Condiments
Confections
Beverages
Condiments
Confections
DescriptionDescription
Soft drinks, coffees
Sweet and savory
Desserts, candies,
Soft drinks, coffees
Sweet and savory
Desserts, candies,
PicturePicture
0x15
0x15
0x15
0x15
0x15
0x15
0x15CheesesDairy Products4
DELETE Categories
WHERE
CategoryID = 4
DELETE Categories
WHERE
CategoryID = 4
USE Northwind
CREATE TRIGGER Category_Delete
ON Categories
FOR DELETE
AS
UPDATE P SET Discontinued = 1
FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryID
USE Northwind
CREATE TRIGGER Category_Delete
ON Categories
FOR DELETE
AS
UPDATE P SET Discontinued = 1
FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryID
ProductsProductsProducts
ProductIDProductID DiscontinuedDiscontinued
12
3
4
1
2
3
4
00
0
0
0
0
0
0
Trigger Actions Execute
2 1
UPDATE P SET Discontinued = 1
FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryID
DELETE Statement to a Table with a DELETE
Statement Defined
DELETE Statement Logged
Trigger Actions Executed
111
222
333
8/9/2019 Module 13 Implementing Triggers
13/36
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 hasa trigger defined on it,
1. the original rows are moved into the Deleted Table
and the,
2. updated rows ( after image) are inserted into theInserted Table.
8/9/2019 Module 13 Implementing Triggers
14/36
How an UPDATE Trigger Works
UPDATE Statement to a table with an UPDATE Trigger Defined
UPDATE Employees
SET EmployeeID = 17
WHERE EmployeeID = 2
UPDATE Employees
SET EmployeeID = 17
WHERE EmployeeID = 2
UPDATE Statement logged as INSERT and DELETE Statements
EmployeesEmployeesEmployees
EmployeeIDEmployeeID LastNameLastName FirstNameFirstName TitleTitle HireDateHireDate
1
2
3
4
1
2
3
4
Davolio
Barr
Leverling
Peacock
Davolio
Barr
Leverling
Peacock
Nancy
Andrew
Janet
Margaret
Nancy
Andrew
Janet
Margaret
Sales Rep.
R
Sales Rep.
Sales Rep.
Sales Rep.
R
Sales Rep.
Sales Rep.
~~~
~~~
~~~
~~~
~~~
~~~
~~~
~~~
2 Fuller Andrew Vice Pres. ~~~
insertedinsertedinserted
1717 FullerFuller AndrewAndrew Vice Pres.Vice Pres. ~~~~~~
deleteddeleteddeleted
22 FullerFuller AndrewAndrew Vice Pres.Vice Pres. ~~~~~~
TRIGGER Actions ExecuteUSE NorthwindGOCREATE TRIGGER Employee_Update
ON EmployeesFOR UPDATE
ASIF UPDATE (EmployeeID)
BEGIN TRANSACTIONRAISERROR ('Transaction cannot be processed.\***** Employee ID number cannot be modified.', 10, 1)ROLLBACK TRANSACTION
USE NorthwindGOCREATE TRIGGER Employee_Update
ON EmployeesFOR UPDATE
ASIF UPDATE (EmployeeID)BEGIN TRANSACTION
RAISERROR ('Transaction cannot be processed.\***** Employee ID number cannot be modified.', 10, 1)ROLLBACK TRANSACTION
ASIF UPDATE (EmployeeID)BEGIN TRANSACTION
RAISERROR ('Transaction cannot be processed.\***** Employee ID number cannot be modified.', 10, 1)ROLLBACK TRANSACTION
Transaction cannot be processed.***** Member number cannot be modifiedTransaction cannot be processed.***** Member number cannot be modified
EmployeesEmployeesEmployees
EmployeeIDEmployeeID LastNameLastName FirstNameFirstName TitleTitle HireDateHireDate
1
2
3
4
1
2
3
4
Davolio
Barr
Leverling
Peacock
Davolio
Barr
Leverling
Peacock
Nancy
Andrew
Janet
Margaret
Nancy
Andrew
Janet
Margaret
Sales Rep.
R
Sales Rep.
Sales Rep.
Sales Rep.
R
Sales Rep.
Sales Rep.
~~~
~~~
~~~
~~~
~~~
~~~
~~~
~~~
2 Fuller Andrew Vice Pres. ~~~
UPDATE Statement to a Table with an UPDATE
Trigger Defined
UPDATE Statement Logged as INSERT andDELETE Statements
Trigger Actions Executed
111
222
333
8/9/2019 Module 13 Implementing Triggers
15/36
Data Updates on Specific Column
Create Triggert_prodON prodFOR Updateas
IF UPDATE ( product )begin
Print Column can not be Updated'rollback transaction
end
8/9/2019 Module 13 Implementing Triggers
16/36
How an INSTEAD OF Trigger Works
Create a View That Combines Two or More TablesCREATE VIEW
Customers AS
SELECT *
FROM CustomersMex
UNION
SELECT *
FROM CustomersGer
CREATE VIEW
Customers AS
SELECT *
FROM CustomersMex
UNION
SELECT *
FROM CustomersGer
CustomersMexCustomersMexCustomersMex
CustomerIDCustomerID CompanyNameCompanyName CountryCountry PhonePhone
ANATR
ANTON
CENTC
ANATR
ANTON
CENTC
Ana Trujill
Antonio M
Centro Co
Ana Trujill
Antonio M
Centro Co
Mexico
Mexico
Mexico
Mexico
Mexico
Mexico
(5) 555-4729
(5) 555-3932
(5) 555-3392
(5) 555-4729
(5) 555-3932
(5) 555-3392
~~~
~~~
~~~
~~~
~~~
~~~
CustomersGerCustomersGerCustomersGer
CustomerIDCustomerID CompanyNameCompanyName CountryCountry PhonePhone
ALFKI
BLAUS
DRACD
ALFKI
BLAUS
DRACD
Alfreds Fu
Blauer Se
Drachenb
Alfreds Fu
Blauer Se
Drachenb
Germany
Germany
Germany
Germany
Germany
Germany
030-0074321
0621-08460
0241-039123
030-0074321
0621-08460
0241-039123
~~~
~~~
~~~
~~~
~~~
~~~
INSTEAD OFtrigger directs the
update to the base
table
CustomersCustomersCustomers
CustomerIDCustomerID CompanyNameCompanyName CountryCountry PhonePhone
ALFKI
ANATR
ANTON
ALFKI
ANATR
ANTON
Alfreds Fu
Ana Trujill
Antonio M
Alfreds Fu
Ana Trujill
Antonio M
Germany
Mexico
Mexico
Germany
Mexico
Mexico
030-0074321
(5) 555-4729
(5) 555-3932
030-0074321
(5) 555-4729
(5) 555-3932
~~~
~~~
~~~
~~~
~~~
~~~Original Insert to
the CustomersView Does Not
Occur
UPDATE is Madeto the View
ALFKI Alfreds Fu Germany 030-0074321 ~~~
ALFKI Alfreds Fu Germany 030-0074321 ~~~
INSTEAD OF Trigger Can Be on a Table or View
The Action That Initiates the Trigger Does NOT Occur
Allows Updates to Views Not Previously Updateable
111
222
333
8/9/2019 Module 13 Implementing Triggers
17/36
Performance Considerations
Triggers Work Quickly Because the inserted anddeleted 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
8/9/2019 Module 13 Implementing Triggers
18/36
Recommended Practices
Keep Definitions as Simple as PossibleKeep Definitions as Simple as Possible
Minimize Use of ROLLBACK in TriggersMinimize Use of ROLLBACK in Triggers
Use Triggers Only When NecessaryUse Triggers Only When Necessary
8/9/2019 Module 13 Implementing Triggers
19/36
Check Your Understanding.
8/9/2019 Module 13 Implementing Triggers
20/36
Q.1 What is a Trigger.?
8/9/2019 Module 13 Implementing Triggers
21/36
Q.2. Triggers are powerful tools that can be used toenforce business rules automatically when data ismodified. ?
1. True
2. False
8/9/2019 Module 13 Implementing Triggers
22/36
Q.3. A Trigger can be Associated with a Table or View.?
1. Yes
2. No
8/9/2019 Module 13 Implementing Triggers
23/36
Q.4. Triggers Are Proactive ; Constraints Are Reactive.
1. True
2. False
8/9/2019 Module 13 Implementing Triggers
24/36
Q.5. Name the Logical Tables that the part of SQL ServerTrigger Architecture.
8/9/2019 Module 13 Implementing Triggers
25/36
Q.6. What is the role of Inserted Table when
Insert Trigger fires.
8/9/2019 Module 13 Implementing Triggers
26/36
Q.7. What is the role of Deleted Table when DeletedTrigger fires.
8/9/2019 Module 13 Implementing Triggers
27/36
Q.8. How an Update Trigger use logical tables differentlythan other DML Statements.
8/9/2019 Module 13 Implementing Triggers
28/36
Q.9. Are there other DML Statements also whichcan make a trigger to fire.
1. Yes
2. No
8/9/2019 Module 13 Implementing Triggers
29/36
Q.10. A trigger can be called directly.
1. True
2. False
8/9/2019 Module 13 Implementing Triggers
30/36
Q.11. You are a consultant tasked with troubleshooting aclient's database. The client has a trigger that is usedto enforce complex referential integrity. The triggerreferences columns in several tables and performs acascading 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.
8/9/2019 Module 13 Implementing Triggers
31/36
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.
8/9/2019 Module 13 Implementing Triggers
32/36
Q.13. You are the administrator of a SQL Server databasenamed Purchasing. You have a DELETE triggeron theWishlist table that has been working for several months.You ask one of your junior staff members to delete therecords from the Wishlist table. He reports later that he hassuccessfully removed the records. You check the deleted
table for the records, but they are not there. What is themost 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.
8/9/2019 Module 13 Implementing Triggers
33/36
Q.14. You are the administrator of a SQL Server databasenamed Training. You have created an INSERT trigger thatupdates the Classes table when new records are added tothe Courses table. You want to verify that the trigger isworking properly and that the updated data is correct.What should you check?
1. Application log
2. Transaction log
3. Inserted table
4. Sysobjects table
8/9/2019 Module 13 Implementing Triggers
34/36
Q.15.A colleague asks you for advice. She is writing acomplex trigger that updates prices in the Sales tablebased on interest rate data updated in the Statistics table.Frequently when the trigger executes, it appears that nochanges 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 triggerexecution.
3. She is using the Rollback Transaction statement in hercode.
4. There is insufficient disk space to execute the trigger.
8/9/2019 Module 13 Implementing Triggers
35/36
Rerview
Introduction to Triggers
Defining Triggers
How Trigger Works
Performance Considerations
8/9/2019 Module 13 Implementing Triggers
36/36
Thank You.