Triggers Specialized stored procedure that runs ‘automatically’ Another method to enforce rules Typically used to enforce business rules not easily done by constraint Often used when need to log actions
DDL v. DML Triggers DDL Triggers allow procedures to run as part of CREATE, ALTER, and DROP statements DML Triggers run in response to data changes – INSERT, UPDATE, DELETE
DML Trigger Types For/After: Fire after the action has occurred (tables only) Changes written to data tables Trigger fires Instead Of: Fire after changes written to logical tables but before written to data tables (tables or views) Trigger fires Changes written to data tables
Respond to actions on data Trigger is not called Trigger is specific to a table (or view) Table can have multiple triggers One trigger can respond to different actions
Triggers & Constraints Constraints give better performance Triggers can span tables, databases, servers; constraints are table specific If testing a value inserted in one table depends on an entry in another table, use a trigger If testing a value depends on an entry in the current row, a relationship, or function result, use a constraint
Related Tables Triggers can use the Inserted and Deleted tables Inserted table holds new or updated records Deleted table holds deleted or original version of updated records
Inserted & Deleted Tables Action Inserted Table Deleted Table Insert XX Update XX XX Delete XX
Triggers for Referential Integrity If trying to enroll a student, add a trigger on insert or update that tests for valid student id in Students table If Exists (Select * from Students Where StudentID IN (Select StudentID From Inserted)) Begin Insert into Enrollments(…) End
Update() Can test whether a column has changed Can use to determine if a calculated field need to be updated Update(columnname) If Update(FirstName) Print ‘FirstName has changed’
Updating Summary Information If tracking Possible Points for a schedule, changing Possible Points for an Assignment would require change to the Schedule’s Possible Points Use Update(PossiblePoints) in trigger for Assignment insert, update
Instead Of Triggers Can have one for each type of action Can apply to views Provides way to allow data modification in joined tables Instead of triggers won’t work if have cascade update or delete Need to complete action! If you’re executing code instead of deleting a row, the row won’t be deleted if you don’t delete it in your code!
A particular slide catching your eye?
Clipping is a handy way to collect important slides you want to go back to later.