Presentation is loading. Please wait.

Presentation is loading. Please wait.

Implementing Triggers

Similar presentations


Presentation on theme: "Implementing Triggers"— Presentation transcript:

1 Implementing Triggers
Advanced Database Dr. AlaaEddin Almabhouh

2 Topic & Structure of Lesson
What Are Triggers? Syntax for Creating Triggers How an INSERT Trigger Works How a DELETE Trigger Works How an UPDATE Trigger Works How an INSTEAD OF Trigger Works Syntax for Altering and Dropping Triggers Slide 2 (of 33)

3 What Are Triggers? Triggers are a powerful tool that enables you to enforce domain, entity, and referential data integrity. SQL code permits you to access only one table for an INSERT, UPDATE, or DELETE statement. The trigger was invented to change related tables at the same time.

4 What Are Triggers? A trigger has the same functionality as a stored procedure. It consists of a predefined set of Transact-SQL code that will execute on demand. Run a stored procedure by using an EXECUTE statement. In contrast, a trigger fires automatically when the event where it is defined occurs—it can never be called directly. When combining triggers and constraints on a table, the constraint fires before the trigger does. If a constraint violation occurs, the trigger won’t fire. The constraint is proactive, whereas the trigger is reactive.

5 Categories of Triggers?
Three categories: AFTER triggers execute after an INSERT, UPDATE, or DELETE statement BEFORE triggers execute before an INSERT, UPDATE, or DELETE statement INSTEAD OF triggers execute instead of an INSERT, UPDATE, or DELETE statement

6 Some facts about triggers
CHECK constraints can reference only the columns on which the column-level or table-level constraint is defined, any cross- table constraints (business rules) must be defined as triggers. Triggers can use to enforce complex business logic that is difficult or impossible to enforce by using other data integrity mechanisms. Triggers can cascade changes through related tables in the database. Triggers can evaluate the state of a table before and after a data modification and take actions based on that difference.

7 Syntax for Creating triggers
Create in current database by using the CREATE TRIGGER statement CREATE TRIGGER [ schema_name. ] trigger_name ON { table | view } { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } AS { sql_statement [ ; ] [ ...n ] }

8 How an INSERT Trigger Works
When an INSERT trigger fires, new rows are added to both the trigger table and the inserted table. The inserted table is a temporary table that holds a copy of the rows that have been inserted. The inserted table allows you to reference logged data from the initiating INSERT statement. The trigger can examine the inserted table to determine whether, or how, the trigger actions should be executed.

9 How an INSERT Trigger Works
1 INSERT statement executed 2 INSERT statement logged 3 AFTER INSERT trigger statements executed CREATE TRIGGER [insrtWorkOrder] ON [Production].[WorkOrder] AFTER INSERT AS BEGIN SET NOCOUNT ON; INSERT INTO [Production].[TransactionHistory]( [ProductID],[ReferenceOrderID],[TransactionType] ,[TransactionDate],[Quantity],[ActualCost]) SELECT inserted.[ProductID],inserted.[WorkOrderID] ,'W',GETDATE(),inserted.[OrderQty],0 FROM inserted; End

10 Example of an INSERT Trigger
This trigger checks to make sure the credit rating for the vendor is good when an attempt is made to insert a new purchase order. CREATE TRIGGER LowCredit ON Purchasing.PurchaseOrderHeader FOR INSERT AS int = v.CreditRating FROM Purchasing.PurchaseOrderHeader p INNER JOIN inserted i ON p.PurchaseOrderID = i.PurchaseOrderID JOIN Purchasing.Vendor v on v.VendorID = i.VendorID = 5 BEGIN RAISERROR ('This vendor''s credit rating is too low to accept new purchase orders.', 16, 1) ROLLBACK TRANSACTION END

11 How an DELETE Trigger Works
When a DELETE trigger is fired, deleted rows from the affected table are placed in a special deleted table. The deleted table is a temporary table that holds a copy of the rows that have been deleted. The deleted table enables you to reference logged data from the initiating DELETE statement.

12 Facts about an DELETE Trigger
When a row is appended to the deleted table, it no longer exists in the database table; therefore, the deleted table and the database tables have no rows in common. Space is allocated from memory to create the deleted table. The deleted table is always in the cache.

13 How a DELETE Trigger Works
DELETE statement executed 1 2 DELETE statement logged 3 AFTER DELETE trigger statements executed CREATE TRIGGER [delCategory] ON [Categories] AFTER DELETE AS BEGIN UPDATE P SET [Discontinued] = 1 FROM [Products] P INNER JOIN deleted as d ON P.[CategoryID] = d.[CategoryID] END;

14 How an UPDATE Trigger Works
When an UPDATE statement is executed on a table that has a trigger defined on it, the original rows (before image) are moved into the deleted table, and the updated rows (after image) are inserted into the inserted table. The trigger can examine the deleted and inserted tables, as well as the updated table, to determine whether multiple rows have been updated and how the trigger actions should be carried out. You can define a trigger to monitor data updates on a specific column by using the IF UPDATE statement.

15 How an UPDATE Trigger Works
1 UPDATE statement executed 2 UPDATE statement logged 3 AFTER UPDATE trigger statements executed CREATE TRIGGER [updtProductReview] ON [Production].[ProductReview] AFTER UPDATE NOT FOR REPLICATION AS BEGIN UPDATE [Production].[ProductReview] SET [Production].[ProductReview].[ModifiedDate] = GETDATE() FROM inserted WHERE inserted.[ProductReviewID] = [Production].[ProductReview].[ProductReviewID]; END;

16 How an INSTEAD OF Trigger Works
This trigger executes instead of the original triggering action. INSTEAD OF triggers increase the variety of types of updates that you can perform against a view. Each table or view is limited to one INSTEAD OF trigger for each triggering action (INSERT, UPDATE, or DELETE). They enable you to code logic that can reject parts of a batch while allowing other parts of a batch to succeed.

17 How an INSTEAD OF Trigger Works
UPDATE, INSERT, or DELETE statement executed 1 2 Executed statement does not occur 3 INSTEAD OF trigger statements executed CREATE TRIGGER [delEmployee] ON [HumanResources].[Employee] INSTEAD OF DELETE NOT FOR REPLICATION AS BEGIN SET NOCOUNT ON; int; = COUNT(*) FROM deleted; > BEGIN … END; END;

18 Syntax for Altering and Dropping Triggers
ALTER TRIGGER DROP TRIGGER ALTER TRIGGER [ schema_name. ] trigger_name ON { table | view } { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } AS { sql_statement [ ; ] [ ...n ] } DROP TRIGGER [ schema_name.] trigger_name

19 Q & A Slide 81 (of 82)


Download ppt "Implementing Triggers"

Similar presentations


Ads by Google