Module 11: Implementing TriggersOverviewIntroduction to TriggersWhat Is a Trigger?Uses of TriggersConsiderations for Using TriggersDefining TriggersCreating TriggersAltering and Dropping TriggersHow Triggers WorkHow an INSERT Trigger WorksHow a DELETE Trigger WorksHow an UPDATE Trigger WorksHow an INSTEAD OF Trigger WorksHow Nested Triggers WorkRecursive TriggersExamples of TriggersEnforcing Data IntegrityEnforcing Business RulesPerformance ConsiderationsRecommended PracticesReviewModule 11: Implementing TriggersOverviewIntroductionDefiningCreate, drop, alter triggersHow Triggers WorkExamplesPerformance ConsiderationsAnalyze performance issues related to triggers Introduction to TriggersWhat Is a Trigger?UsesConsiderations for Using TriggersWhat Is a Trigger?Associated with a TableInvoked AutomaticallyCannot Be Called DirectlyIs Part of a TransactionAlong with the statement that calls the triggerCan ROLLBACK transactions (use with care)Uses of TriggersCascade Changes Through Related Tables in a DatabaseA delete or update trigger can cascade changes to related tables: Soda name change to change in soda name in Sells tableEnforce More Complex Data Integrity Than a CHECK ConstraintChange prices in case of price rip-offs.Define Custom Error MessagesMaintain Denormalized DataAutomatically update redundant data.Compare Before and After States of Data Under ModificationConsiderations for Using TriggersTriggers Are Reactive; Constraints Are ProactiveConstraints Are Checked FirstTables Can Have Multiple Triggers for Any ActionTable Owners Can Designate the First and Last Trigger to Fire You Must Have Permission to Perform All Statements That Define TriggersTable Owners Cannot Create AFTER Triggers on Views or Temporary Tables Defining TriggersCreating TriggersAltering and Dropping TriggersCreating TriggersRequires Appropriate PermissionsCannot Contain Certain Statements Use NorthwindGOCREATE TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 1BEGIN RAISERROR( 'You cannot delete more than one employee at a time.', 16, 1) ROLLBACK TRANSACTIONENDUse NorthwindGOCREATE TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 1BEGIN RAISERROR( 'You cannot delete more than one employee at a time.', 16, 1) ROLLBACK TRANSACTIONENDAltering and Dropping TriggersAltering a TriggerChanges the definition without dropping the triggerCan disable or enable a triggerDropping a TriggerUSE NorthwindGOALTER TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 6BEGIN RAISERROR( 'You cannot delete more than six employees at a time.', 16, 1) ROLLBACK TRANSACTIONENDUSE NorthwindGOALTER TRIGGER Empl_Delete ON EmployeesFOR DELETE ASIF (SELECT COUNT(*) FROM Deleted) > 6BEGIN RAISERROR( 'You cannot delete more than six employees at a time.', 16, 1) ROLLBACK TRANSACTIONEND How Triggers WorkHow an INSERT Trigger WorksHow a DELETE Trigger WorksHow an UPDATE Trigger WorksHow an INSTEAD OF Trigger WorksHow Nested Triggers WorkRecursive TriggersHow an INSERT Trigger WorksINSERT 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 DetailsOrder DetailsOrderIDOrderID105221052310524105221052310524ProductIDProductID1041710417UnitPriceUnitPrice31.009.6530.0031.009.6530.00QuantityQuantity79247924DiscountDiscount0.20.150.00.20.150.0 5 19.002 0.210523Insert statement loggedinsertedinsertedinsertedinserted10523105232219.0019.00550.20.2TRIGGER Actions ExecuteOrder DetailsOrder DetailsOrder DetailsOrder DetailsOrderIDOrderID105221052310524105221052310524ProductIDProductID1041710417UnitPriceUnitPrice31.009.6530.0031.009.6530.00QuantityQuantity79247924DiscountDiscount0.20.150.00.20.150.0 5 19.002 0.210523Trigger Code:USE NorthwindCREATE TRIGGER OrdDet_InsertON [Order Details]FOR INSERTASUPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity)FROM Products AS P INNER JOIN Inserted AS ION P.ProductID = I.ProductIDTrigger Code:USE NorthwindCREATE TRIGGER OrdDet_InsertON [Order Details]FOR INSERTASUPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity)FROM Products AS P INNER JOIN Inserted AS ION P.ProductID = I.ProductIDUPDATE P SET UnitsInStock = (P.UnitsInStock – I.Quantity)FROM Products AS P INNER JOIN Inserted AS ION P.ProductID = I.ProductIDProductsProductsProductsProductsProductIDProductIDUnitsInStockUnitsInStock…………1234123415106520151065202 15INSERT Statement to a Table with an INSERTTrigger DefinedINSERT Statement LoggedTrigger Actions Executed111122223333How a DELETE Trigger WorksDELETE Statement to a table with a DELETE Trigger DefinedDELETE Statement to a table with a DELETE Trigger DefinedDeletedDeletedDeletedDeleted44Dairy ProductsDairy ProductsCheesesCheeses0x15…0x15…DELETE statement loggedCategoriesCategoriesCategoriesCategoriesCategoryIDCategoryID123123CategoryNameCategoryNameBeveragesCondimentsConfectionsBeveragesCondimentsConfectionsDescriptionDescriptionSoft drinks, coffees…Sweet and savory …Desserts, candies, …Soft drinks, coffees…Sweet and savory …Desserts, candies, …PicturePicture0x15…0x15…0x15…0x15…0x15…0x15… 0x15…CheesesDairy Products4DELETE CategoriesWHERE CategoryID = 4DELETE CategoriesWHERE CategoryID = 4USE NorthwindCREATE TRIGGER Category_DeleteON CategoriesFOR DELETEASUPDATE P SET Discontinued = 1FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryIDUSE NorthwindCREATE TRIGGER Category_DeleteON CategoriesFOR DELETEASUPDATE P SET Discontinued = 1FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryIDProductsProductsProductsProductsProductIDProductIDDiscontinuedDiscontinued…………1234123400000000Trigger Actions Execute2 1UPDATE P SET Discontinued = 1FROM Products AS P INNER JOIN deleted AS dON P.CategoryID = d.CategoryIDDELETE Statement to a Table with a DELETEStatement DefinedDELETE Statement LoggedTrigger Actions Executed111122223333How an UPDATE Trigger WorksUPDATE Statement to a table with an UPDATE Trigger DefinedUPDATE EmployeesSET EmployeeID = 17WHERE EmployeeID = 2UPDATE EmployeesSET EmployeeID = 17WHERE EmployeeID = 2UPDATE Statement logged as INSERT and DELETE
View Full Document