2014-06-25 60 views
4

我需要在表中標識多個列更新並將它們存儲在審計表中。
這裏是審計模式:在觸發器中查找多個更新的列

auditid auditTimestamps updateFieldName oldFieldValue newFieldValue 

我們有一個架構中的另一個表員工:

EmpID EmpName Age Address1 Phone 

我對員工架構寫道更新觸發器,當一條記錄被更新時,觸發器被啓動,在觸發我檢查哪些字段值已更新並在審計表架構上維護此信息。

For checking field for update , i have used below code sample: 

    BEGIN 
      if update(empName) 
      begin 
       set @updatedcolumnname='empName'; 
       set @newvendorname=(SELECT empNameFROM inserted); 
       set @oldvendorname=(SELECT empNameFROM deleted); 
       //Here insert logic that insert above find values into audit table. 
      end 

       // Same check for all remaining fields(Age,Address1,Phone) 
    END 

但它似乎不適合我。它會將所有更新且未更新的列插入到審計表中。

請建議如何實現以上功能。

感謝

回答

0

您可以在觸發使用merge命令而不是INSERT命令。

SELECT 'empName' AS FieldName, d.empName AS OldValue, i.empName AS NewValue 
FROM Inserted i 
INNER JOIN deleted d ON d.EmpID = i.EmpID 
WHERE i.EmpName<>d.ImpName 

UNION ALL 

SELECT 'Age', d.Age, i.Age 
FROM Inserted i 
INNER JOIN deleted d ON d.EmpID = i.EmpID 
WHERE i.Age<>d.Age 

UNION ALL 

SELECT 'Address1', d.Address1, i.Address1 
FROM Inserted i 
INNER JOIN deleted d ON d.EmpID = i.EmpID 
WHERE i.Address1<>d.Address1 

UNION ALL 

SELECT 'Phone', d.Phone, i.Phone 
FROM Inserted i 
INNER JOIN deleted d ON d.EmpID = i.EmpID 
WHERE i.Phone<>d.Phone 

所以你的查詢:

MERGE AuditTable AS Destination 
USING (
     SELECT 'empName' AS FieldName, d.empName AS OldValue, i.empName AS NewValue 
     FROM Inserted i 
     INNER JOIN deleted d ON d.EmpID = i.EmpID 
     WHERE i.EmpName<>d.ImpName 

     UNION ALL 

     SELECT 'Age', d.Age, i.Age 
     FROM Inserted i 
     INNER JOIN deleted d ON d.EmpID = i.EmpID 
     WHERE i.Age<>d.Age 

     UNION ALL 

     SELECT 'Address1', d.Address1, i.Address1 
     FROM Inserted i 
     INNER JOIN deleted d ON d.EmpID = i.EmpID 
     WHERE i.Address1<>d.Address1 

     UNION ALL 

     SELECT 'Phone', d.Phone, i.Phone 
     FROM Inserted i 
     INNER JOIN deleted d ON d.EmpID = i.EmpID 
     WHERE i.Phone<>d.Phone 

    ) AS SOURCE ON SOURCE.FieldName = Destination.UpdateFieldName 
       AND SOURCE.OldValue = Destination.OldFieldValue 
       AND SOURCE.NewValue = Destinatino.NewFieldValue 
    WHEN MATCHED THEN UPDATE SET OldFieldValue = OldValue, 
           NewFieldValue = NewValue 
    WHEN NOT MATCHED THEN INSERT (UpdateFieldName, OldFieldValue, NewFieldValue) 
         VALUES(FieldName, OldValue,NewValue) 
+0

SQL服務器顯示「無效列名‘ID’」您也可以通過下面的查詢計算你改變列爲d.Id = i.Id.pls建議如何解決這個問題。 –

+0

@Atu Tha.I編輯我的帖子。我必須使用EmpID而不是Id。 –

+0

thx man.for your reply。 –