Use cases for INSTEAD OF triggers (DML)

Building and Optimizing Triggers in SQL Server

Florin Angelescu

Instructor

General use of INSTEAD OF triggers

  • Prevent operations from happening
  • Control database statements
  • Enforce data integrity
Building and Optimizing Triggers in SQL Server

Triggers that prevent changes

CREATE TRIGGER PreventProductChanges
ON Products
INSTEAD OF UPDATE
AS
    RAISERROR ('Updates of products are not permitted.
                Contact the database administrator if a change is needed.', 16, 1);
Building and Optimizing Triggers in SQL Server

Triggers that prevent and notify

CREATE TRIGGER PreventCustomersRemoval
ON Customers
INSTEAD OF DELETE
AS
    DECLARE @EmailBodyText NVARCHAR(50) =
                       (SELECT 'User "' + ORIGINAL_LOGIN() +
                        '" tried to remove a customer from the database.');

    RAISERROR ('Customer entries are not subject to removal.', 16, 1);

    EXECUTE SendNotification @RecipientEmail = '[email protected]'
                              ,@EmailSubject = 'Suspicious database behavior'
                              ,@EmailBody = @EmailBodyText;
Building and Optimizing Triggers in SQL Server

Triggers with conditional logic

CREATE TRIGGER ConfirmStock
ON Orders
INSTEAD OF INSERT
AS
    IF EXISTS (SELECT * FROM Products AS p
               INNER JOIN inserted AS i ON i.Product = p.Product
               WHERE p.Quantity < i.Quantity)
        RAISERROR ('You cannot place orders when there is no product stock.', 16, 1);
    ELSE
        INSERT INTO dbo.Orders (Customer, Product, Quantity, OrderDate, TotalAmount)
        SELECT Customer, Product, Quantity, OrderDate, TotalAmount FROM inserted;
Building and Optimizing Triggers in SQL Server

Triggers with conditional logic

Conditional Logic for Triggers

Building and Optimizing Triggers in SQL Server

Let's practice!

Building and Optimizing Triggers in SQL Server

Preparing Video For Download...