Search code examples
sqltriggerssql-server-2012audit

SQL Server 2012 trigger: Auditing. How to see previous value of a row without shadow table


I am trying to create an auditing table. I have a table called person.address in the AdventureWorks 2012 database.

I am using a trigger to capture changes to the table, the only problem is I do not know if it is possible to use a trigger to capture a row BEFORE it is edited. I am trying to save resources and overheads so trying to not use a shadow table. I know there is no "Before Insert" trigger. But is there any way to capture the information contained in a row, and when someone does an insert or update, this row can be written to my audit.table before the insert is completed?

Thank you.


Solution

  • Given a simplistic table with two rows:

    CREATE TABLE dbo.foo(a INT PRIMARY KEY);
    
    INSERT dbo.foo(a) VALUES(1),(2);
    

    Then an update trigger simply to demonstrate:

    CREATE TRIGGER dbo.trfoo ON dbo.foo FOR UPDATE
    AS
    BEGIN
      SET NOCOUNT ON;
    
      SELECT a FROM inserted;
    
      SELECT a FROM deleted;
    END
    GO
    

    The result of an action, such as:

    UPDATE dbo.foo SET a += 1;
    

    Results in:

    a    -- this is the *new* version of these rows
    ----
    3
    2
    
    a    -- this is the *old* version of these rows
    ----
    2
    1
    

    Also, there is an INSTEAD OF INSERT trigger, which allows you to perform actions before the insert (they're not called BEFORE triggers because you still have to perform the insert yourself). More info here.