Module 10: Implementing Triggers
Overview Introducing Triggers Creating, Altering, and Dropping Triggers Working with Triggers Implementing Triggers
Lesson: Introducing Triggers SQL Server Triggers What Are Triggers Used For? Sequence of Events and Restrictions
SQL Server Triggers Associated with a Table Invoked Automatically Cannot Be Called Directly Is Part of a Transaction Can include a ROLLBACK TRANSACTION statement If a ROLLBACK TRANSACTION statement is encountered, the entire transaction rolls back.
What Are Triggers Used For? Cascade Changes Through Related Tables Enforce More Complex Data Integrity Define Custom Error Messages Maintain Denormalized Data Compare Before and After States of Data Under Modification
Sequence of Events and Restrictions 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
Lesson: Creating, Altering, and Dropping Triggers The CREATE TRIGGER Statement The ALTER TRIGGER Statement The DROP TRIGGER Statement
The CREATE TRIGGER Statement Requires Appropriate Permissions Cannot Contain Certain Statements USE Northwind GO CREATE TRIGGER Empl_Delete ON Employees FOR DELETE AS IF @@ROWCOUNT > 1 BEGIN RAISERROR( 'You cannot delete more than one employee at a time.', 16, 1) ROLLBACK TRANSACTION END
The ALTER TRIGGER Statement Altering a Trigger Changes the definition without dropping the trigger Can disable or enable a trigger USE Northwind GO ALTER TRIGGER Empl_Delete ON Employees FOR DELETE AS IF @@ROWCOUNT > 6 BEGIN RAISERROR( 'You cannot delete more than six employees at a time.', 16, 1) ROLLBACK TRANSACTION END
The DROP TRIGGER Statement Dropping a Trigger Dropped automatically when its associated table is dropped Information is removed from the sysobjects and syscomments Required Permission The table owner Members of sysadmin Members of db_owner USE Northwind GO DROP TRIGGER Empl_Delete
Lesson: Working with Triggers How INSERT Triggers Work How DELETE Triggers Work How UPDATE Triggers Work How INSTEAD OF Triggers Work How Nested Triggers Work Recursive Triggers
How INSERT Triggers Work INSERT Statement to a Table with an INSERT Trigger Defined 1 Trigger Actions Executed 3 INSERT Statement Logged 2 How INSERT Triggers Work Trigger Code: USE Northwind CREATE TRIGGER OrdDet_Insert ON [Order Details] FOR INSERT AS UPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity) FROM Products AS P INNER JOIN Inserted AS I ON P.ProductID = I.ProductID INSERT statement to a table with an INSERT Trigger Defined TRIGGER Actions Execute INSERT [Order Details] VALUES (10525, 2, 19.00, 5, 0.2) OrderID ProductID UnitPrice Quantity Discount 10522 10 31.00 7 0.2 10523 41 9.65 9 0.15 10524 30.00 24 0.0 10525 2 19.00 5 0.2 Insert statement logged OrderID ProductID UnitPrice Quantity Discount 10522 10 31.00 7 0.2 10523 41 9.65 9 0.15 10524 30.00 24 0.0 10525 2 19.00 5 Products ProductID UnitsInStock … 1 15 2 10 3 65 4 20 Products ProductID UnitsInStock … 1 15 2 5 3 65 4 20 inserted 10525 2 19.00 5 0.2
How DELETE Triggers Work Trigger Actions Execute DELETE Statement to a table with a DELETE Trigger Defined DELETE Statement to a Table with a DELETE Statement Defined 1 Trigger Actions Executed 3 DELETE Statement Logged 2 USE Northwind CREATE TRIGGER Category_Delete ON Categories FOR DELETE AS UPDATE P SET Discontinued = 1 FROM Products AS P INNER JOIN deleted AS d ON 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 d ON P.CategoryID = d.CategoryID DELETE Categories WHERE CategoryID = 4 Categories CategoryID CategoryName Description Picture 1 Beverages Soft drinks, coffees… 0x15… 2 Condiments Sweet and savory … 3 Confections Desserts, candies, … Categories CategoryID CategoryName Description Picture 1 Beverages Soft drinks, coffees… 0x15… 2 Condiments Sweet and savory … 3 Confections Desserts, candies, … 4 Dairy Products Cheeses Products ProductID Discontinued … 1 2 3 4 Products ProductID Discontinued … 1 2 3 4
How UPDATE Triggers Work UPDATE Statement to a Table with an UPDATE Trigger Defined 1 Trigger Actions Executed 3 UPDATE Statement Logged as INSERT and DELETE Statements 2 UPDATE Statement to a table with an UPDATE Trigger Defined TRIGGER Actions Execute USE Northwind GO CREATE TRIGGER Customer_Update ON Customers FOR UPDATE AS IF UPDATE (CustomerID) BEGIN RAISERROR ('Transaction cannot be processed.\ ***** Customer ID cannot be modified.', 10, 1) ROLLBACK TRANSACTION END UPDATE Customers SET CustomerID = ‘AHORN’ WHERE CustomerID = ‘AROUT’ Customers CustomerID CompanyName .. ALFKI Alfreds Futterkiste ~~~ ANATR Ana Trujillo Emparedados y helados ANTON Antonio Moreno Taquería AROUT Around the Horn Customers CustomerID CompanyName .. ALFKI Alfreds Futterkiste ~~~ ANATR Ana Trujillo Emparedados y helados ANTON Antonio Moreno Taquería AROUT Around the Horn UPDATE Statement logged as INSERT and DELETE Statements Transaction cannot be processed. ***** Customer ID cannot be modified inserted AHORN Around the Horn ~~~ deleted AROUT Around the Horn ~~~
How INSTEAD OF Triggers Work Create a View That Combines Two or More Tables CREATE VIEW Customers AS SELECT * FROM CustomersMex UNION SELECT * FROM CustomersGer UPDATE is Made to the View INSTEAD OF trigger directs the update to the base table Original Insert to the Customers View Does Not Occur Customers CustomerID CompanyName Country Phone … ALFKI Alfreds Fu… Germany 030-0074321 ~~~ ANATR Ana Trujill… Mexico (5) 555-4729 ANTON Antonio M… (5) 555-3932 Customers CustomerID CompanyName Country Phone … ALFKI Alfreds Fu… Germany 030-0074321 ~~~ ANATR Ana Trujill… Mexico (5) 555-4729 ANTON Antonio M… (5) 555-3932 Customers CustomerID CompanyName Country Phone … ALFKI Alfreds Fu… Germany 030-0074321 ~~~ ANATR Ana Trujill… Mexico (5) 555-4729 ANTON Antonio M… (5) 555-3932 INSTEAD OF Trigger Can Be on a Table or View 1 The Action That Initiates the Trigger Does NOT Occur 2 Allows Updates to Views Not Previously Updateable 3 CustomersMex CustomerID CompanyName Country Phone … ANATR Ana Trujill… Mexico ANTON Antonio M… CENTC Centro Co… CustomersGer CustomerID CompanyName Country Phone … ALFKI Alfreds Fu… Germany 030-0074321 ~~~ BLAUS Blauer Se… 0621-08460 DRACD Drachenb… 0241-039123 CustomersGer CustomerID CompanyName Country Phone … ALFKI Alfreds Fu… Germany 030-0074321 ~~~ BLAUS Blauer Se… 0621-08460 DRACD Drachenb… 0241-039123 CustomersGer CustomerID CompanyName Country Phone … ALFKI Alfreds Fu… Germany 030-0074321 ~~~ BLAUS Blauer Se… 0621-08460 DRACD Drachenb… 0241-039123
How Nested Triggers Work Order_Insert Order Details OrderID ProductID UnitPrice Quantity Discount 10522 10 31.00 7 0.2 10523 41 9.65 9 0.15 10524 30.00 24 0.0 10525 2 19.00 5 Placing an order causes the Order_Insert trigger to execute InStock_Update Products ProductID UnitsInStock … 1 15 2 3 65 4 20 Executes an UPDATE statement on the Products table InStock_Update trigger executes UnitsInStock + UnitsOnOrder is < ReorderLevel for ProductID 2 Sends message
Recursive Triggers Activating a Trigger Recursively Types of Recursive Triggers Direct recursion Indirect recursion Determining Whether to Use Recursive Triggers
Lesson: Implementing Triggers Performance Considerations Best Practices Example: Auditing with Triggers Example: Enforcing Business Rules
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
ü ü ü ü Best Practices 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 ü
Example: Auditing with Triggers Employees EmployeeID … Salary 1 30,000 2 40,000 3 4 UPDATE Employees SET Salary=40000 WHERE EmployeeId = 2 Updated CREATE TRIGGER Salary_Audit ON Employees FOR UPDATE AS… Trigger Inserts Row AuditLog EntryID EntryDate UserID Activity 1 2005/6/2 dbo Modified Salary of EmployeeID: 2 From 30000 To 40000
Example: Enforcing Business Rules Products with Outstanding Orders Cannot Be Deleted IF (Select Count (*) FROM [Order Details] INNER JOIN deleted ON [Order Details].ProductID = deleted.ProductID ) > 0 ROLLBACK TRANSACTION DELETE statement executed on Product table Trigger code checks the Order Details table Products ProductID UnitsInStock … 1 15 2 10 3 65 4 20 Products ProductID UnitsInStock … 1 15 3 65 4 20 Products ProductID UnitsInStock … 1 15 2 10 3 65 4 20 Order Details OrderID ProductID UnitPrice Quantity Discount 10522 10 31.00 7 0.2 10523 2 19.00 9 0.15 10524 41 9.65 24 0.0 10525 30.00 'Transaction cannot be processed' 'This product has order history' Transaction rolled back
Lab A: Creating Triggers Exercise 1: Creating Triggers Exercise 2: Creating a Trigger for Updating Derived Data Exercise 3: Creating a Trigger That Maintains a Complex Business Rule Exercise 4: Testing the Firing Order of Constraints and Triggers