2015-05-19 61 views
4

PFB的scipts需要過濾從AUDIT表中的記錄爲特定列

步驟-1(審覈表)

CREATE TABLE AuditTest 
(
    ID INT 
    ,col1 NVARCHAR(MAX) 
    ,col2 NVARCHAR(MAX) 
    ,col3 NVARCHAR(MAX) 
    ,col4 NVARCHAR(MAX) 
    ,[Action] VARCHAR(10) 
    ,[Date] DATETIME DEFAULT GETDATE() 
) 

步驟2(事務表)

CREATE TABLE Test11 
(
    ID INT IDENTITY 
    ,col1 NVARCHAR(MAX) 
    ,col2 NVARCHAR(MAX) 
    ,col3 NVARCHAR(MAX) 
    ,col4 NVARCHAR(MAX) 
) 

步驟-3(Update觸發器上的事務表)

CREATE TRIGGER trgAudit ON Test11 
AFTER UPDATE 
AS 
BEGIN 
INSERT INTO AuditTest(ID 
,col1 
,col2 
,col3 
,col4 
,[Action] 
) 
SELECT d.ID,d.col1,d.col2,d.col3,d.col4,'o' FROM DELETED d 
INSERT INTO AuditTest(ID 
,col1 
,col2 
,col3 
,col4 
,[Action] 
) 
SELECT i.ID,i.col1,i.col2,i.col3,i.col4,'n' FROM INSERTED i 
END 

步驟4(插入和上事務表更新)

insert into Test11 
select 'a','a','a','a' 

UPDATE Test11 
SET col1 = 'b' 
WHERE ID = 1 


UPDATE Test11 
SET col2 = 'z' 
WHERE ID = 1 

需要選擇所有新記錄(WHERE ACTION =「N」)從表AuditTest 如果任何更新用於列造「COL1」只有

注意:不想在觸發器內添加任何腳本。

由於提前, 阿尼爾

+0

如果您想在AuditTest表上添加一個新的字段,即審計順序標識,那麼您可以將其與以前的審計記錄進行比較,並查看列中某個特定值是否已更改。在這種情況下,我總是完成以下一項或兩項操作......將觸發器代碼更改爲僅對某些更改進行插入操作,或者,或添加新的操作代碼,以便更新哪些列被隱藏在操作代碼中。 n1 n2 n3 n4 n24 n14 n0 –

回答

0

對於每個ID,這會給你col1是隻做

WITH cte1 AS 
(SELECT ROW_NUMBER() OVER (Partition BY ID ORDER BY DATE ASC, ACTION DESC) RowNum, 
      * 
    FROM AuditTest 
) 
, cte2 AS 
(SELECT ROW_NUMBER() OVER (Partition BY ID ORDER BY DATE ASC, ACTION DESC) RowNum, 
      * 
    FROM AuditTest 
) 
SELECT cte2.ID, 
     cte2.col1, 
     cte2.col2, 
     cte2.col3, 
     cte2.col4, 
     cte2.action, 
     cte2.date 
FROM cte1, cte2 
WHERE cte2.RowNum > cte1.RowNum AND 
     cte2.id = cte1.id AND 
     cte2.col1 != cte1.col1 AND 
     cte2.col2=cte1.col2 AND 
     cte2.col3=cte1.col3 AND 
     cte2.col4=cte1.col4 AND 
     cte2.Date = cte1.Date 

運行這些查詢一次一個的所有更新(等待更新間隔秒數聲明)測試解決方案

TRUNCATE TABLE Test11; 
TRUNCATE TABLE AuditTest; 
insert into Test11 
select 'a','a','a','a' 
insert into Test11 
SELECT 'b', 'b', 'b', 'b' 

UPDATE Test11 
SET col1 = 'b' 
WHERE ID = 1; 

UPDATE TEST11 
SET col1='c' 
WHERE ID = 2; 


UPDATE Test11 
SET col2 = 'z' 
WHERE ID = 1; 

UPDATE Test11 
SET col2='z' 
WHERE ID=2; 

UPDATE Test11 
SET col1='bd' 
WHERE ID=2; 

結果

1 b a a a n 2015-05-19 22:33:15.430 
2 c b b b n 2015-05-19 22:33:20.690 
2 bd z b b n 2015-05-19 22:35:22.427