Search code examples
sqlsql-serversql-server-2008auditing

Using table auditing in order to have "snapshots" of table


I need a solution for the following problem:

I will have a table in SQL server 2008 that will be changing daily. It's a small table with maybe 5000 rows at most and around 5 fields.

The client will need the ability to view all the data in the table the way it was at a given point in time. For example "show me what all the data looked like in the table 2 weeks ago".

Someone had mentioned that auditing the table with http://autoaudit.codeplex.com/ would solve this problem.

My questions:

  1. Is there a solution to this problem that would involve simple auditing?
  2. If so, then how would i use auditing to solve this problem?
  3. Is there a different solution already in existence for this sort of challenge so that I do not have to reinvent the wheel?

Solution

  • Have an auditing table that get's manipulated by triggers. Something like:

    create table YourAuditTable
    (
        -- all of your source table's columns
        CreateDate datetime not null,
        DeleteDate datetime null
    )
    go
    

    And your trigger would look like this:

    create trigger AuditYourTable
    on dbo.YourTable
    after insert, update, delete
    as
    
        if exists(select * from inserted)
        begin
            if exists(select * from deleted)
            begin
                -- this is for an update
                update YourAuditTable
                set DeleteDate = getdate()
                where YourIDCol in (select YourIDCol from deleted)
            end 
    
            -- this is just for an insert
            insert into YourAuditTable
            select *, getdate() as CreateDate
            from inserted
        end
        else
        begin
            -- this is just for a delete
            update YourAuditTable
            set DeleteDate = getdate()
            where YourIDCol in (select YourIDCol from deleted)
        end
    
    go
    

    What this will allow you to do is query your audit table for a point in time. In other words, just use DATEDIFF to determine if a row was created prior to that given point in time, and deleted after it (or not deleted at all).

    EDIT

    To query your audit table for point in time data:

    select *
    from YourAuditTable
    where CreateDate <= @PointInTimeDateTime
    and
    (
        DeleteDate is null or
        DeleteDate > @PointInTimeDateTime
    )