You are on page 1of 29

Module 11

Responding to Data Manipulation


Via Triggers
Module Overview

Designing DML Triggers


Implementing DML Triggers
• Advanced Trigger Concepts
Lesson 1: Designing DML Triggers

What Are DML Triggers?


AFTER Triggers vs. INSTEAD OF Triggers
Inserted and Deleted Virtual Tables
SET NOCOUNT ON
• Considerations for Triggers
What Are DML 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


AFTER Triggers vs. INSTEAD OF 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
Inserted and Deleted Virtual Tables

• 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
SET NOCOUNT ON

• 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
Considerations for 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


Lesson 2: Implementing DML Triggers

AFTER INSERT Triggers


Demonstration: Working with AFTER INSERT
Triggers
AFTER DELETE Triggers
Demonstration: Working with AFTER DELETE
Triggers
AFTER UPDATE Triggers
• Demonstration: Working with AFTER UPDATE
Triggers
AFTER INSERT Triggers

• INSERT statement is executed


• AFTER INSERT trigger then fires
• Ensures that multirow inserts are supported
Demonstration: Working with AFTER INSERT
Triggers

In this demonstration, you will see how to:


• Create an AFTER INSERT trigger
AFTER DELETE Triggers

• DELETE statement is executed


• AFTER DELETE trigger then fires
• Multirow deletes
• Truncate table
Demonstration: Working with AFTER DELETE
Triggers

In this demonstration, you will see how to:


• Create and test AFTER DELETE triggers
AFTER UPDATE Triggers

• UPDATE statement is executed


• AFTER UPDATE trigger then fires
• Trigger processes updated rows at the same time
Demonstration: Working with AFTER UPDATE
Triggers

In this demonstration, you will see how to:


• Create and test AFTER UPDATE triggers
Lesson 3: Advanced Trigger Concepts

INSTEAD OF Triggers
Demonstration: Working with INSTEAD OF Triggers
How Nested Triggers Work
Considerations for Recursive Triggers
UPDATE Function
Firing Order for Triggers
Alternatives to Triggers
• Demonstration: Replacing Triggers with Computed
Columns
INSTEAD OF 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
Demonstration: Working with INSTEAD OF
Triggers

In this demonstration, you will see how to:


• Create and test an INSTEAD OF DELETE trigger
How Nested Triggers Work

• Turned on at the server level


• Complex to debug
Considerations for Recursive 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
UPDATE Function

• UPDATE function—is a column being updated?


• Used in AFTER INSERT and AFTER UPDATE
• COLUMNS UPDATED function returns bitmap of
columns being updated
Firing Order for 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
Alternatives to 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
Demonstration: Replacing Triggers with
Computed Columns

In this demonstration, you will see:


• How to replace a trigger with a computed
column
Lab: Responding to Data Manipulation by Using
Triggers

Exercise 1: Create and Test the Audit Trigger


• Exercise 2: Improve the Audit Trigger

Logon Information
Virtual Machine: 20762C-MIA-SQL
User name: ADVENTUREWORKS\Student
Password: Pa55w.rd

Estimated Time: 30 minutes


Lab Scenario

You are required to audit any changes to data in a


table that contains sensitive balance data. You
have decided to implement this by using DML
triggers because the SQL Server Audit mechanism
does not provide directly for the requirements in
this case.
Lab Scenario (Continued)

Supporting Documentation
The Production.ProductAudit table is used to hold
changes to high value products. The data to be
inserted in each column is shown in the following
table:

Column Data type Value to insert


AuditID int IDENTITY
ProductID int ProductID
UpdateTime datetime2 SYSDATETIME()
ModifyingUser varchar(30) ORIGINAL_LOGIN()
OriginalListPrice decimal(18,2) ListPrice before update
NewListPrice decimal(18,2) ListPrice after update
Lab Review

• In this lab exercise you learnt how to create and


modify triggers. You created and modified a
trigger to write an entry into a table, triggered by
an update made to a column in another table.
Module Review and Takeaways

Review Question(s)
• Best Practice

You might also like