简体   繁体   English

SQL Server创建审核触发器

[英]SQL Server create audit trigger

I need to create an audit record for table changes. 我需要为表更改创建审核记录。 I was reading the following answer: SQL Insert/Update/Delete Trigger Efficiency 我正在阅读以下答案: SQL插入/更新/删除触发器效率

My audit table has the following columns: 我的审核表包含以下列:

audit_id
audit_date
audit_user
audit_table_name -> table name being audited
audit_table_id -> id of the row being audited
audit_parent_name -> parent table name if this table is a child
audit_parent_id -> parent id (is a foreign key in this table)
audit_type -> insert, update, delete
audit_fields -> all fields that were affected

The tricky part is that audit_fields has the following format: 棘手的部分是audit_fields具有以下格式:

column_name + chr(1) + old_value + chr(1) + new_value + chr(10) ...

Can this be achieved with a trigger and how exactly? 可以通过触发器实现它吗?

EDIT: 编辑:

I'm basing my trigger on the following answer: SQL Server auto audit updated column 我将触发器基于以下答案:“ SQL Server自动审核更新”列

The trigger works fine if I use that same table. 如果我使用同一张表,则触发器可以正常工作。 However, how can I concatenate the changed fields in the format I need and insert just 1 record in the audit table? 但是,如何将更改后的字段以所需的格式连接起来,并在审核表中仅插入1条记录?

Here is simple example of using INSTEAD OF UPDATE trigger to capture before and after value of column and storing it into another table. 这是使用INSTEAD OF UPDATE触发器捕获列的值之前和之后并将其存储到另一个表中的简单示例。

IF OBJECT_ID('dbo.test1') IS NOT NULL DROP TABLE test1
IF OBJECT_ID('dbo.test2') IS NOT NULL DROP TABLE test2

CREATE TABLE Test1 ( Id INT, value VARCHAR(20) )
GO
CREATE  TABLE Test2 (TableName VARCHAR(100), ValueChanged VARCHAR(250) )
GO
CREATE TRIGGER test1_Update ON dbo.Test1
    INSTEAD OF UPDATE
AS
    INSERT INTO dbo.Test2
            ( TableName
            ,ValueChanged
            )
            SELECT 'Test1'
                    ,'value' + ' ' + t.value + ' ' + i.value + ';'
                FROM INSERTED AS i
                JOIN Test1 AS t
                    ON i.id = t.id;
    UPDATE dbo.Test1
        SET value = INSERTED.value
        FROM INSERTED
        WHERE test1.Id = INSERTED.id
go

SELECT * FROM test1

INSERT INTO dbo.Test1 VALUES (1, 'Data'),(2,'Data')

SELECT * FROM test1

UPDATE test1 
SET value = 'MyNew Data 1 '
WHERE id = 1

SELECT * FROM test1
SELECT * FROM test2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM