Best way to implement an audit trail in SQL Server?

后端 未结 7 2319
臣服心动
臣服心动 2020-11-27 03:23

I don\'t know if these requirements are standard or not but I\'m wondering is there a solution out there which can do the following:

  • For a specified set of tab
7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 04:02

    I create trigger which does it for XML this way we can log all tables to same table, making it more flexible

    CREATE TABLE [dbo].[AuditAll] (
        AuditId    int           NOT NULL IDENTITY(1,1),
        [DateTime] datetime      NOT NULL,
        TableName  nvarchar(255) NOT NULL,
        AuditEntry xml           NULL,
    
        CONSTRAINT [PK_AuditAll] PRIMARY KEY CLUSTERED ( AuditId ASC )
    )
    

    I needed only 'old' values, so I store deleted table only, inserted table can be seen in the table anyhow.

    CREATE TRIGGER AuditSimple 
        ON Simple
        AFTER INSERT,DELETE,UPDATE
    AS 
    BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    
    IF (SELECT COUNT(*) FROM deleted) > 0 
    begin
        Declare @AuditMessage XML
        --set valut to all xml from deleted table
        set @AuditMessage = (select * from deleted for xml auto) 
    
        insert into AuditAll( DateTime, TableName, AuditEntry ) 
            values ( GetDate(), 'Simple', @AuditMessage )
    end
    
    END
    GO
    

    I guess this could easily be called in sp_foreach to create it for each table in datatabase but we did not needed it at the moment, just remember to change your table names

    cheers

提交回复
热议问题