IC Improve Code Recipes

Recipe 2.6 · C#

Auditing Changes: Triggers vs Temporal Tables

Problem

Someone changed a customer's credit limit, and the business wants to know who, when and what it was before. The answer depends on an audit mechanism that was put in years ago. About 1,128 SQL files in my archive create triggers, across 18 engagements, and many of those triggers are audit triggers that only work for one row at a time.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

SQL
-- Not to copy: assumes a single-row update.
CREATE TRIGGER trg_Customer_Update ON Customer
FOR UPDATE
AS
DECLARE @Id int, @OldLimit money, @NewLimit money
SELECT @Id = CustomerId, @OldLimit = CreditLimit FROM deleted
SELECT @NewLimit = CreditLimit FROM inserted
INSERT INTO CustomerAudit (CustomerId, OldLimit, NewLimit,
                           ChangedBy, ChangedOn)
VALUES (@Id, @OldLimit, @NewLimit, SUSER_SNAME(), GETDATE())

A trigger fires once per statement, not once per row. An UPDATE that changes 300 customers fills inserted and deleted with 300 rows each, and this trigger records one of them, picked arbitrarily. It also records every update, even when nothing changed, and SUSER_SNAME() is the application's service account, not the person.

The improved recipe

A set-based audit trigger:

SQL
CREATE TABLE dbo.CustomerAudit
(
    AuditId        BIGINT IDENTITY(1, 1) NOT NULL
                   CONSTRAINT PK_CustomerAudit PRIMARY KEY,
    CustomerId     INT            NOT NULL,
    Action         CHAR(1)        NOT NULL,  -- I, U or D
    OldName        NVARCHAR(200)  NULL,
    NewName        NVARCHAR(200)  NULL,
    OldCreditLimit DECIMAL(19, 4) NULL,
    NewCreditLimit DECIMAL(19, 4) NULL,
    ChangedUtc     DATETIME2(3)   NOT NULL,
    ChangedBy      NVARCHAR(128)  NOT NULL
);
GO

CREATE OR ALTER TRIGGER dbo.Customer_Audit
ON dbo.Customer
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS (SELECT 1 FROM inserted)
       AND NOT EXISTS (SELECT 1 FROM deleted)
        RETURN;

    DECLARE @ChangedBy NVARCHAR(128) = COALESCE(
        CAST(SESSION_CONTEXT(N'AppUser') AS NVARCHAR(128)),
        SUSER_SNAME());

    INSERT INTO dbo.CustomerAudit
        (CustomerId, Action, OldName, NewName,
         OldCreditLimit, NewCreditLimit, ChangedUtc, ChangedBy)
    SELECT COALESCE(i.CustomerId, d.CustomerId),
           CASE WHEN d.CustomerId IS NULL THEN 'I'
                WHEN i.CustomerId IS NULL THEN 'D'
                ELSE 'U'
           END,
           d.Name, i.Name,
           d.CreditLimit, i.CreditLimit,
           SYSUTCDATETIME(),
           @ChangedBy
    FROM   inserted AS i
    FULL OUTER JOIN deleted AS d
           ON d.CustomerId = i.CustomerId
    WHERE  d.CustomerId IS NULL
       OR  i.CustomerId IS NULL
       OR  EXISTS (SELECT i.Name, i.CreditLimit
                   EXCEPT
                   SELECT d.Name, d.CreditLimit);
END;

A system-versioned temporal table (SQL Server 2016 and later):

SQL
ALTER TABLE dbo.Customer ADD
    ValidFrom DATETIME2(3) GENERATED ALWAYS AS ROW START HIDDEN
        NOT NULL
        CONSTRAINT DF_Customer_ValidFrom DEFAULT SYSUTCDATETIME(),
    ValidTo   DATETIME2(3) GENERATED ALWAYS AS ROW END HIDDEN
        NOT NULL
        CONSTRAINT DF_Customer_ValidTo
            DEFAULT CONVERT(DATETIME2(3), '9999-12-31 23:59:59.999'),
    PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo);
GO

ALTER TABLE dbo.Customer
    SET (SYSTEM_VERSIONING = ON
         (HISTORY_TABLE = dbo.CustomerHistory));
GO

-- What did customer 42 look like at the end of June?
SELECT c.CustomerId, c.Name, c.CreditLimit
FROM   dbo.Customer
       FOR SYSTEM_TIME AS OF '2025-06-30T23:59:59' AS c
WHERE  c.CustomerId = 42;

How it works

The trigger joins inserted and deleted with a FULL OUTER JOIN on the key, so it handles inserts (no deleted row), deletes (no inserted row) and updates (both) for any number of rows in one statement. The EXISTS ... EXCEPT test compares old and new values in a way that treats two NULLs as equal, so updates that change nothing are not audited.

SESSION_CONTEXT (SQL Server 2016 and later) carries the real user name from the application. Right after opening the connection, the application runs EXEC sys.sp_set_session_context @key = N'AppUser', @value = @UserName; with the signed-in user as a parameter. Pooled connections clear the session context when they are reset, so one request's user does not leak into the next.

A temporal table takes a different approach. SQL Server keeps every previous version of every row in a history table automatically, with the period columns showing when each version was current. You query the past with FOR SYSTEM_TIME AS OF, BETWEEN or ALL, and no trigger code is involved. Marking the period columns HIDDEN keeps them out of SELECT * and out of existing INSERT statements that do not list columns.

Need Audit trigger Temporal table
Who made the change Yes, via session context Only if a column stores it
Point-in-time queries Hard Built in
Selected columns only Yes No, full rows

Variations and pitfalls

  • Temporal tables do not record who. Add a ModifiedBy column that the application sets on every write. Deletes still lose the user, because the deleted row's last version shows the previous editor. If you need to know who deleted a row, add a small delete trigger or use soft deletes.
  • History grows forever. Set HISTORY_RETENTION_PERIOD (SQL Server 2017 and later and Azure SQL Database), or archive old history yourself.
  • Schema changes to a temporal table are applied to its history table automatically for most ALTER TABLE operations, but some changes require turning versioning off and back on in one transaction.
  • Keep triggers small. No cursors, no e-mail, no calls to other databases. A trigger runs inside the caller's transaction, so its errors and its slowness belong to every insert and update on the table.
  • Change Data Capture and SQL Server Audit are other options. CDC suits feeding a warehouse; SQL Server Audit suits security auditing of reads and permission changes.