2014-03-26 183 views
0

我需要爲表更改創建審計記錄。我讀了以下的答案: SQL Insert/Update/Delete Trigger EfficiencySQL Server創建審計觸發器

我的審計表有以下幾列:

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 

棘手的部分是audit_fields的格式如下:

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

才能實現這一目標帶觸發器,具體如何?

編輯:

我我的基礎上觸發如下回答: SQL Server auto audit updated column

如果我使用相同的表,觸發器工作正常。但是,如何以我需要的格式連接更改的字段並在審計表中只插入1條記錄?

回答

0

這裏是使用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