SQL Triggers

This document provides a comprehensive guide to SQL triggers, their functionality, syntax, and best practices within Microsoft SQL Server.

What is a Trigger?

A trigger is a special type of stored procedure that automatically executes or is fired when an event occurs in the database. These events are typically data manipulation language (DML) statements such as INSERT, UPDATE, or DELETE operations on a specific table.

Types of Triggers

DML Triggers in Detail

DML triggers are the most common type. They can be classified further:

Syntax for Creating a DML Trigger

CREATE TRIGGER trigger_name
ON table_name
[ FOR | AFTER | INSTEAD OF ]
[ INSERT, UPDATE, DELETE ]
[ WITH EXECUTE AS { 'user' | SELF | OWNER } ]
AS
BEGIN
    -- Trigger logic goes here
END;

Special Trigger Tables

Within a trigger, you can access two special, undeclared tables:

Example: Logging Changes to a Table

Logging Table Updates

This trigger logs any updates to the Employees table into an AuditLog table.

CREATE TRIGGER trg_Employee_Update
ON Employees
AFTER UPDATE
AS
BEGIN
    IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS (SELECT * FROM deleted) -- INSERT operation
    BEGIN
        INSERT INTO AuditLog (TableName, Action, UserID, Timestamp)
        SELECT 'Employees', 'INSERT', inserted.EmployeeID, GETDATE()
        FROM inserted;
    END
    ELSE IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted) -- UPDATE operation
    BEGIN
        INSERT INTO AuditLog (TableName, Action, UserID, Timestamp)
        SELECT 'Employees', 'UPDATE', inserted.EmployeeID, GETDATE()
        FROM inserted;
    END
    ELSE IF NOT EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted) -- DELETE operation
    BEGIN
        INSERT INTO AuditLog (TableName, Action, UserID, Timestamp)
        SELECT 'Employees', 'DELETE', deleted.EmployeeID, GETDATE()
        FROM deleted;
    END
END;

Common Use Cases for Triggers

Best Practices

API Reference (Common Commands)

Command Description
CREATE TRIGGER Creates a new trigger.
ALTER TRIGGER Modifies an existing trigger.
DROP TRIGGER Removes a trigger.
sp_helptrigger Lists triggers for a specified table or database.

For more advanced trigger types and detailed information, please refer to the official Microsoft SQL Server documentation.