Download presentation
Presentation is loading. Please wait.
1
Responding to Data Manipulation Via Triggers
20762B 11: Responding to Data Manipulation Via Triggers Module 11 Responding to Data Manipulation Via Triggers
2
Lesson 1: Designing DML Triggers
20762B Lesson 1: Designing DML Triggers 11: Responding to Data Manipulation Via Triggers Considerations for Triggers Question Which types of statements fire DML triggers? ( )Option 1: CREATE, ALTER, DROP ( )Option 2: MERGE, ALTER, DELETE ( )Option 3: MERGE, CREATE, INSERT ( )Option 4: CREATE, UPDATE, DELETE ( )Option 5: DELET, INSERT, UPDATE Answer (√) Option -2: DELET, INSERT, UPDATE What reasons can you think of for deploying AFTER triggers? Common reasons for implementing AFTER triggers are: Providing auditing of the changes that were made. Implementing complex rules involving the relationship between tables. Implementing default values or calculated values within rows.
3
Triggers are special stored procedures which:
20762B What Are DML Triggers? 11: Responding to Data Manipulation Via Triggers Triggers are special stored procedures which: Fire for INSERT, UPDATE, or DELETE DML operations Fire on DDL statements such as CREATE, ALTER, or DROP Provide complex logic and meaningful error messages Multiple triggers can be fired Use this slide to discuss what a trigger is and how it executes when data is modified. Remind the students that cascading referential integrity constraints were discussed earlier. Don’t discuss each type of trigger, because the triggers are addressed individually in the following topics. Also, note that DDL triggers and LOGON triggers are out of scope for this course, but an example of a DDL trigger is provided in the XML modules. More detail will be provided in later slides.
4
AFTER Triggers vs. INSTEAD OF Triggers
20762B AFTER Triggers vs. INSTEAD OF Triggers 11: Responding to Data Manipulation Via Triggers Two types of triggers can be implemented in managed code or Transact-SQL: AFTER triggers Fire after the event to which they relate Are treated as part of the same transaction as the statement that triggered them Can roll back the statement that triggered them (and any transaction of which that statement was part) INSTEAD OF triggers Make it possible to execute alternate code, unlike a BEFORE trigger in other database engines Are often used to create updatable views with more than one base table Use this slide to discuss what a trigger is and how it executes when data is modified. Remind the students that cascading referential integrity constraints were discussed earlier. Don’t discuss each type of trigger, because the triggers are addressed individually in the following topics. Also, note that DDL triggers and LOGON triggers are out of scope for this course but an example of a DDL trigger is included in the XML modules. More detail will be provided in later slides.
5
Inserted and Deleted Virtual Tables
11: Responding to Data Manipulation Via Triggers Inserted and deleted virtual tables Provide access to state of the data before and after the modification began Are often joined to the modified table data Are available in both AFTER and INSTEAD OF triggers Deleted table DELETE statements – rows just deleted UPDATE statements – original row contents Inserted table INSERT statements – rows just inserted UPDATE statements – modified row contents Inserted and deleted virtual tables are used so that, during the execution of a trigger, you can access both the modified and unmodified versions of the data. Having access to both modified and unmodified versions often requires a join between the table data and the virtual table. These tables only exist for the duration of the triggers and in the same scope as the triggers. For example, if the trigger calls a stored procedure, that procedure cannot see these tables. These tables are also available in INSTEAD OF triggers.
6
SET NOCOUNT ON Triggers should not return rows of data
20762B SET NOCOUNT ON 11: Responding to Data Manipulation Via Triggers Triggers should not return rows of data Client applications often check the number of rows that are affected by data modification statements Triggers that are affected by data modification statements SET NOCOUNT ON avoids affecting the outer statements Returning rowsets has been deprecated Use the configuration setting “disallow results from triggers” to prevent triggers from returning resultsets If a client application updates three rows of a table, it often checks the returned rowcount to make sure that only three rows are affected. Adding a trigger to the table could cause this count to change (and the application to fail) if the trigger also performed data modification. To avoid this, most triggers should have SET NOCOUNT ON within the trigger body. SET operations within a trigger remain in effect during the execution of the trigger, but then revert to their previous settings. Triggers should generally never return rows of data. In future versions, the ability to do so will be removed. To prevent triggers for returning result sets in SQL Server, set the configuration setting “disallow results from triggers” to 1. Use the example in the subject matter to describe how SET NOCOUNT ON is used.
7
Considerations for Triggers
20762B Considerations for Triggers 11: Responding to Data Manipulation Via Triggers Constraints: Are preferred to triggers Avoid data modification overhead on violation Triggers: Are complex to debug Use a rowversion store in tempdb database Excessive usage can impact tempdb performance Can increase the duration of transactions Managing Trigger Security Wherever possible, you should use constraints rather than triggers. Constraint violations avoid the statements ever occurring. Trigger rollbacks have to undo the work performed after it has been done. In earlier versions of SQL Server, the inserted and deleted virtual tables were essentially implemented like a view over the transaction log—the data had to be reconstructed to make it available for them. From SQL Server 2005 onwards, the inserted and deleted virtual tables have been created using the rowversion store held in tempdb. This improves trigger performance but excess trigger usage can adversely affect the performance of tempdb. Avoid implementing too much business logic within triggers because they can be quite tricky to debug. Ensure that the students are aware of the security issues of executing DDL and DML triggers.
8
Lesson 2: Implementing DML Triggers
20762B Lesson 2: Implementing DML Triggers 11: Responding to Data Manipulation Via Triggers Demonstration: Working with AFTER UPDATE Triggers Question Is the following statement true or false? “When rows are deleted from a table by using a DELETE statement, any AFTER DELETE triggers are fired when the deletion is completed. DELETE ROWS is an administrative option that removes all rows from a table.” ( )False ( )True Answer (√)False Analyze this create trigger code and indicate the four errors. You can assume the table and columns have been created. Outline some code you could use to test the trigger. CREATE TRIGGER TR_SellingPrice_InsertUpdate IN dbo.SellingPrice AFTER INPUT, UPDATE AS BEGIN SET NOCOUNT OPEN; INSERT sp SET sp.ExtendedAmount = sp.SubTotal + sp.TaxAmount + sp.FreightAmount FROM dbo.SellingPrice AS sp INNER JOIN inserted AS i ON sp.SellingPriceID = i.SellingPriceId; END; GO (More notes on the next slide)
9
INSERT statement is executed AFTER INSERT trigger then fires
20762B AFTER INSERT Triggers 11: Responding to Data Manipulation Via Triggers INSERT statement is executed AFTER INSERT trigger then fires Ensures that multirow inserts are supported An INSERT trigger executes whenever an INSERT statement inserts data into a table or a view on which the trigger is configured. Walk the students through the CREATE TRIGGER statement example. Explain the function of every statement within the trigger. In particular, note the use of SET NOCOUNT ON. Also note that the trigger works with multiple rows of data. It is important to avoid writing triggers that only work for a single row.
10
DELETE statement is executed AFTER DELETE trigger then fires
20762B AFTER DELETE Triggers 11: Responding to Data Manipulation Via Triggers DELETE statement is executed AFTER DELETE trigger then fires Multirow deletes Truncate table A DELETE trigger is a special kind of stored procedure that executes whenever a DELETE statement deletes data from a table or a view on which the trigger is configured. You may want to use a DELETE trigger when the record being deleted has referring records and you want to update or eliminate the references. For example, if you have an Authors table and a Books table, you may want to delete the books associated when an author is deleted. While this could be done with cascading referential integrity, you might also use the DELETE trigger to move records to an audit or archive table when they are deleted, or to execute more complex logic. Point out to students that DELETE triggers are not executed for TRUNCATE TABLE operations.
11
UPDATE statement is executed AFTER UPDATE trigger then fires
20762B AFTER UPDATE Triggers 11: Responding to Data Manipulation Via Triggers UPDATE statement is executed AFTER UPDATE trigger then fires Trigger processes updated rows at the same time An UPDATE trigger executes whenever an UPDATE statement changes data in a table or a view on which the trigger is configured. Walk the students through the CREATE TRIGGER example on the slide.
12
Lesson 3: Advanced Trigger Concepts
20762B Lesson 3: Advanced Trigger Concepts 11: Responding to Data Manipulation Via Triggers Demonstration: Replacing Triggers with Computed Columns Question What are the four missing terms from this statement indicated by <XXX>? <XXX> These triggers are most commonly used to enable views that are based on multiple base tables to be updatable. You can define <XXX> triggers on views that have one or more base tables, where they can extend the types of updates that a view can support. This trigger executes instead of the original triggering action. <XXX> triggers increase the variety of types of updates that you can perform against a view. Each table or view is limited to one <xxx> trigger for each triggering action (<XXX>). You can specify an <XXX> trigger on both tables and views. You cannot create an <XXX> trigger on views that have the <XXX> clause defined. You can perform operations on the base tables within the trigger. This avoids the trigger being called again. For example, you could perform a set of checks before inserting data, and then perform the insert on the base table. ( )Option 1: How Nested Triggers Work; INSTEAD OF; DELETE; CHECK OPTION ( )Option 2: Updatable Views; AFTER INSERT; INSERT, UPDATE, or DELETE; NO ROWCOUNT ( )Option 3: Updatable Views; INSTEAD OF; DML or DDL; CHECK OPTION ( )Option 4: Updatable Views; RATHER THAN; UPDATE; CHECK OPTION ( )Option 5: Updatable Views; INSTEAD OF; INSERT, UPDATE, or DELETE; CHECK OPTION Answer (√) Option -2: Updatable Views; INSTEAD OF; INSERT, UPDATE, or DELETE; CHECK OPTION
13
INSERT, UPDATE or DELETE statement requested to be executed
INSTEAD OF Triggers 11: Responding to Data Manipulation Via Triggers INSERT, UPDATE or DELETE statement requested to be executed Statement does not execute INSTEAD OF trigger code executes instead Updatable views are a common use An INSTEAD OF trigger is executed in place of the usual triggering action. Walk the students through the CREATE TRIGGER statement and explain the options used. In the example, we are making sure that products are flagged as discontinued when someone tries to delete them.
14
How Nested Triggers Work
20762B How Nested Triggers Work 11: Responding to Data Manipulation Via Triggers Turned on at the server level Complex to debug Nested triggers are ON by default and set as a server level option. Any trigger can contain an UPDATE, INSERT, or DELETE statement that affects another table. Triggers are nested when a trigger performs an action that initiates another trigger. Triggers can be nested up to 32 levels. Stress that nested triggers can be disabled by an administrator at the server level.
15
Considerations for Recursive Triggers
20762B Considerations for Recursive Triggers 11: Responding to Data Manipulation Via Triggers Recursive triggers are disabled by default To turn them on: ALTER DATABASE db SET RECURSIVE_TRIGGERS ON Direct Recursion Indirect Recursion Considerations: Careful design and testing to ensure that the 32-level nesting limit is not exceeded Difficult to control the order of table updates Can usually be replaced by nonrecursive logic The RECURSIVE TRIGGERS option only affects direct recursion Use this slide to explain how recursive triggers happen and the important considerations. Mention that nested triggers are a server option, which is ON by default, and recursive triggers are a database option, which is OFF by default. A recursive trigger performs an action that causes the same trigger to fire again, either directly or indirectly—just as in the previous slide, except that the trigger points back to the same table (direct) or a trigger fired from another table as a result points back to the table (indirect). You can use the RECURSIVE_TRIGGERS database option to enable or disable direct recursion in triggers. You use the SQL Server nested triggers configuration to enable or disable indirect recursion.
16
UPDATE function—is a column being updated?
11: Responding to Data Manipulation Via Triggers UPDATE function—is a column being updated? Used in AFTER INSERT and AFTER UPDATE COLUMNS UPDATED function returns bitmap of columns being updated It is important to note that the value is not related to whether the value in a column is being updated, only to whether or not the column is one of the columns that is being updated. Even if a value is being changed to the same value it already has, it will be included by this function. Mention that the COLUMNS_UPDATED function can be used to retrieve a bitmap indicating which columns are being updated. However, it is much harder to use than the UPDATE function and depends upon the positional information for the column. Hard-coding that positional information in a trigger affects the maintainability of your trigger code. It also makes the code far less readable.
17
Firing Order for Triggers
20762B Firing Order for Triggers 11: Responding to Data Manipulation Via Triggers Multiple triggers may be created for a single event You cannot specify the order in which the triggers will fire With sp_settriggerorder, you can specify which triggers will fire first and last In general, you should not depend on the order that triggers fire in. SQL Server determines the order. sp_settriggerorder does provide some control over this by specifying which triggers fire first and last. If you specify both first and last, the triggers must be different. @order can be First, Last, or None. None is the default and specifies undefined order. @stmttype is the statement type and can be INSERT, UPDATE, or DELETE for DML triggers.
18
Alternatives to Triggers
20762B Alternatives to Triggers 11: Responding to Data Manipulation Via Triggers Many developers use triggers in situations where alternatives would be preferable: Use constraints for checking values Use defaults for values not supplied during inserts Use foreign key constraints to check for referential integrity Use computed and persisted computed columns Use indexed views for precalculating aggregates Many database developers use triggers to implement most of their integrity checking. In general, this is not a good practice. Stress that triggers are not the answer to every problem. Instead, you should use the appropriate object that is designed for the task. For example, many users create triggers to maintain columns that could be computed columns. Computed columns are a better option for this. In addition, computed columns are less likely to be disabled than triggers.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.