0% found this document useful (0 votes)
11 views28 pages

Responding To Data Manipulation Via Triggers

Module 15 covers the design and implementation of DML triggers in SQL, explaining their types, functionalities, and considerations. It includes lessons on AFTER and INSTEAD OF triggers, their use cases, and advanced concepts such as nested triggers and alternatives to triggers. The module concludes with a lab exercise focused on auditing changes in a marketing campaign balance table using DML triggers.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views28 pages

Responding To Data Manipulation Via Triggers

Module 15 covers the design and implementation of DML triggers in SQL, explaining their types, functionalities, and considerations. It includes lessons on AFTER and INSTEAD OF triggers, their use cases, and advanced concepts such as nested triggers and alternatives to triggers. The module concludes with a lab exercise focused on auditing changes in a marketing campaign balance table using DML triggers.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Module 15

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
• Trigger Considerations
What Are DML Triggers?

Triggers are special stored procedures that execute when


events occur. DML triggers fire on INSERT, UPDATE, DELETE.

Other types of triggers:


• DDL triggers fire on statements like CREATE, ALTER, DROP
• Logon triggers fire when a session is established
AFTER Triggers vs. INSTEAD OF Triggers

• AFTER triggers

• Fire after the event that they relate to


• 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 that statement was part of)
• INSTEAD OF triggers

• Allow executing alternate code – unlike a BEFORE trigger in


other database engines
• Are often used to create updatable views with more than one
base table
• Both can be implemented in managed code or T-SQL
Inserted and Deleted Virtual Tables
• Inserted and deleted Virtual Tables

• Allow us to access the state of the data before and after the
modification began
• Virtual tables are often joined to the modified table data
• Available in both AFTER and INSTEAD OF triggers

Statement inserted deleted


INSERT rows just inserted
DELETE rows just deleted
UPDATE modified row contents original row contents
SET NOCOUNT ON
• Triggers should not return rows of data
• Client applications often check the number of rows
affected by data modification statements
• Triggers should generally not change that count
• SET NOCOUNT ON avoids affecting outer statement

The configuration setting ‘disallow results from triggers’ can be


used to prevent triggers from returning resultsets
Trigger Considerations
• Constraints are preferred to triggers
• Triggers are complex to debug
• Constraints avoid data modification overhead on violation
• Triggers use a rowversion store in tempdb database
• Excess trigger usage can impact tempdb performance
• Triggers can increase the duration of transactions
Lesson 2: Implementing DML Triggers
• AFTER INSERT Triggers
• Demonstration 2A: Working with AFTER INSERT Triggers
• AFTER DELETE Triggers
• Demonstration 2B: Working with AFTER DELETE Triggers
• AFTER UPDATE Triggers
• Demonstration 2C: Working with AFTER UPDATE Triggers
AFTER INSERT Triggers

• INSERT statement is executed


• AFTER INSERT trigger then fires
• Ensure multi-row INSERTs are supported

CREATE
CREATE TRIGGER
TRIGGER TR_Opportunity_Insert
TR_Opportunity_Insert
ON
ON Sales.Opportunity
Sales.Opportunity
AFTER
AFTER INSERT
INSERT AS
AS
BEGIN
BEGIN
SET
SET NOCOUNT
NOCOUNT ON;
ON;
INSERT
INSERT INTO
INTO Sales.OpportunityAudit
Sales.OpportunityAudit
(OpportunityID,
(OpportunityID, ActionPerformed,
ActionPerformed, ActionOccurredAt)
ActionOccurredAt)
SELECT
SELECT i.OpportunityID,
i.OpportunityID,
'I',
'I',
SYSDATETIME()
SYSDATETIME()
FROM
FROM inserted
inserted AS
AS i;
i;
END;
END;
Demonstration 2A: Working with AFTER INSERT Triggers

In this demonstration you will see how to:


• Create an AFTER INSERT trigger
• Test the trigger action
• Drop the trigger
AFTER DELETE Triggers

• DELETE statement is executed


• AFTER DELETE trigger then fires

CREATE TRIGGER
TRIGGER TR_Category_Delete
TR_Category_Delete
ON
ON Product.Category
Product.Category
AFTER
AFTER DELETE
DELETE AS
AS
BEGIN
BEGIN
SET
SET NOCOUNT
NOCOUNT ON;
ON;
UPDATE
UPDATE pp SET
SET p.Discontinued
p.Discontinued == 1
FROM
FROM Product.Product
Product.Product AS
AS p
WHERE
WHERE EXISTS
EXISTS (SELECT
(SELECT 1
1 FROM
FROM deleted
deleted AS
AS d
d
WHERE
WHERE p.CategoryID
p.CategoryID = d.CategoryID);
d.CategoryID);
END;
END;
GO
GO
Demonstration 2B: Working with AFTER DELETE
Triggers

In this demonstration you will see how to:


• Create an AFTER DELETE trigger
• Test the trigger
• Drop the trigger
AFTER UPDATE Triggers

• UPDATE statement is executed


• AFTER UPDATE trigger then fires

CREATE
CREATE TRIGGER
TRIGGER TR_ProductReview_Update
TR_ProductReview_Update
ON
ON Product.ProductReview
Product.ProductReview
AFTER
AFTER UPDATE
UPDATE AS
AS
BEGIN
BEGIN
SET
SET NOCOUNT
NOCOUNT ON;
ON;
UPDATE
UPDATE pr
pr
SET
SET pr.ModifiedDate
pr.ModifiedDate == SYSDATETIME()
SYSDATETIME()
FROM
FROM Product.ProductReview
Product.ProductReview ASAS pr
pr
INNER
INNER JOIN
JOIN inserted
inserted AS
AS ii
ON
ON i.ProductReviewID
i.ProductReviewID == pr.ProductReviewID;
pr.ProductReviewID;
END;
END;
Demonstration 2C: Working with AFTER UPDATE
Triggers

In this demonstration, you will see how to:


• Create an AFTER UPDATE trigger
• Test the trigger
• Query the sys.triggers view
Lesson 3: Advanced Trigger Concepts
• INSTEAD OF Triggers
• Demonstration 3A: Working with INSTEAD OF Triggers
• How Nested Triggers Work
• Considerations for Recursive Triggers
• UPDATE Function
• Trigger Firing Order
• Alternatives to Using Triggers
• Demonstration 3B: 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

CREATE
CREATE TRIGGER
TRIGGER TR_ProductReview_Delete
TR_ProductReview_Delete
ON
ON Product.ProductReview
Product.ProductReview
INSTEAD
INSTEAD OFOF DELETE
DELETE AS
AS
BEGIN
BEGIN
SET
SET NOCOUNT
NOCOUNT ON;
ON;
UPDATE
UPDATE pr
pr SET pr.Discontinued
pr.Discontinued =
= 11
FROM
FROM Product.ProductReview
Product.ProductReview AS
AS pr
pr
INNER
INNER JOIN
JOIN deleted
deleted as
as d
d
ON
ON pr.ProductReviewID
pr.ProductReviewID =
= d.ProductReviewID;
d.ProductReviewID;
END;
END;
Demonstration 3A: Working with INSTEAD OF Triggers

In this demonstration, you will see how to:


• Create an INSTEAD OF DELETE trigger
• Test the trigger
How Nested Triggers Work

INSERT, UPDATE, or
1 DELETE statement

3…and so on…
2
Trigger executes
INSERT, UPDATE,
or DELETE on
another table…
Considerations for Recursive Triggers

Disabled by default – to enable:

ALTER
ALTER DATABASE
DATABASE MarketDev
MarketDev
SET
SET RECURSIVE_TRIGGERS
RECURSIVE_TRIGGERS ON
ON

Considerations:
• Careful design and thorough testing to ensure that the 32 level
nesting limit is not exceeded
• Can be difficult to control the order of table updates
• Can usually be replaced with non-recursive logic
• Option only affects direct recursion
UPDATE Function
• UPDATE determines if a particular column is being updated
• Used in triggers AFTER INSERT or AFTER UPDATE

CREATE
CREATE TRIGGER
TRIGGER TR_Product_Update_ListPriceAudit
TR_Product_Update_ListPriceAudit
ON
ON Production.Product
Production.Product
AFTER
AFTER UPDATE
UPDATE AS
AS
BEGIN
BEGIN
IF
IF UPDATE(ListPrice)
UPDATE(ListPrice)
BEGIN
BEGIN
INSERT
INSERT INTO
INTO Production.ListPriceAudit
Production.ListPriceAudit
(ProductID,
(ProductID, ListPrice,
ListPrice, ChangedWhen)
ChangedWhen)
SELECT
SELECT i.ProductID,
i.ProductID,
i.ListPrice,
i.ListPrice,
SYSDATETIME()
SYSDATETIME()
FROM
FROM inserted
inserted AS
AS i;
i;
END;
END;
END;
END;
Trigger Firing Order

• Multiple triggers may be created for a single event


• You cannot specify the order that the triggers will fire
• sp_settriggerorder allows you to specify which triggers will fire
first and last

EXEC
EXEC sp_settriggerorder
sp_settriggerorder
@triggername=
@triggername=
'Production.TR_Product_Update_ListPriceAudit',
'Production.TR_Product_Update_ListPriceAudit',
@order='First',
@order='First',
@stmttype
@stmttype =
= 'UPDATE';
'UPDATE';
Alternatives to Using Triggers

Many developers use triggers in situations where other


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 pre-calculating aggregates
Demonstration 3B: Replacing Triggers with
Computed Columns

In this demonstration you will see how a trigger could be


replaced by a computed column
Lab 15: Responding to Data Manipulation via Triggers
• Exercise 1: Create the Audit Trigger
• Challenge Exercise 2: Improve the Audit Trigger (Only if
time permits)

Logon information

Virtual machine 10776A-MIA-SQL1

User name AdventureWorks\Administrator


Password Pa$$w0rd

Estimated time: 45 minutes


Lab Scenario

The Marketing.CampaignBalance table holds details of


amounts of money still available for each of the marketing
campaigns the company is undertaking. Changes to the
balances are considered quite sensitive.
You are required to audit any changes to data in the table.
You have decided to implement this via DML triggers as the
requirements in this case are not provided for directly by
the SQL Server Audit mechanism.
Lab Review
• What advantages does the use of triggers for auditing
provide over other options?
• What did you need to specify as well as the trigger’s name
when altering it?
Module Review and Takeaways
• Review Questions

• Best Practices

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy