Database Triggers

This section provides comprehensive documentation on database triggers in SQL Server. Triggers are special stored procedures that automatically execute or are fired when an event occurs in the database server. These events can be Data Manipulation Language (DML) statements (INSERT, UPDATE, DELETE) or Data Definition Language (DDL) statements (CREATE, ALTER, DROP).

What are Triggers?

Triggers are a powerful feature of SQL Server that allows you to enforce business rules, maintain data integrity, and automate complex tasks within the database. They are associated with specific tables or schema objects and are executed in response to a specific event.

Types of Triggers

Creating DML Triggers

DML triggers are commonly used for auditing, enforcing complex constraints, or cascading changes. They can be set to fire AFTER or INSTEAD OF the triggering event.

Example: AFTER INSERT Trigger

This trigger logs new employee records into an audit table.


CREATE TRIGGER AuditNewEmployees
ON Employees
AFTER INSERT
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @EmployeeID INT;
    SELECT @EmployeeID = EmployeeID FROM inserted;

    INSERT INTO AuditLog (EventType, TableName, RecordID, EventTimestamp)
    VALUES ('INSERT', 'Employees', @EmployeeID, GETDATE());
END;
            

Example: INSTEAD OF Trigger

This trigger provides a custom action when an UPDATE occurs on a view.


CREATE TRIGGER UpdateEmployeeView
ON vw_EmployeeDetails
INSTEAD OF UPDATE
AS
BEGIN
    SET NOCOUNT ON;
    
    UPDATE Employees
    SET FirstName = i.FirstName, LastName = i.LastName
    FROM Employees e
    JOIN inserted i ON e.EmployeeID = i.EmployeeID;

    UPDATE EmployeeAddresses
    SET AddressLine1 = i.AddressLine1, City = i.City
    FROM EmployeeAddresses ea
    JOIN inserted i ON ea.EmployeeID = i.EmployeeID;
END;
            

Creating DDL Triggers

DDL triggers are useful for managing schema changes, preventing certain operations, or auditing database structure modifications.

Example: DDL Trigger to Prevent Dropping Tables

This trigger prevents users from dropping tables in the database.


CREATE TRIGGER PreventTableDrop
ON ALL SERVER
FOR DROP_TABLE
AS
BEGIN
    PRINT 'Dropping tables is not allowed.';
    ROLLBACK;
END;
            

Managing Triggers

Best Practices