假设我有一个包含一列的表(是主键),我在该表上有触发器来记录任何更改。现在,当在Deleted中更新一行(主键)时,我有旧的主值,而在Inserted中我有新的主值。在多行更新中,如何将旧值(已删除)与新值(在已插入中)绑定?
e.g:
myTable有一列(也是主键):
PK
---
1
2
现在我更新1到4和2到3
Deleted
-------
1
2
Inserted
--------
3
4
如何在具有三列的审计表中记录这些更改:PK,old_value,new_value
Audit Table
-----------
PK | old_value | new_value
1 | 1 | 4
2 | 2 | 3
在oracle中我们有旧的和新的值,但是在sql server no。中
答案 0 :(得分:-1)
在触发器中使用光标记录更改:
Declare @AuditTable Table (PK Int, OldID int, [NewID] Int)
Declare @OldID Int,
@NewID Int
Declare C1 Cursor For
Select ID
From Inserted
Declare C2 Cursor For
Select ID
From Deleted
Open C1
Open C2
Fetch Next From C1 Into @NewID
Fetch Next From C2 Into @OldID
While @@FETCH_STATUS=0 Begin
Insert Into @AuditTable(PK, OldID, [NewID])
Values (@OldID, @OldID, @NewID)
Fetch Next From C1 Into @NewID
Fetch Next From C2 Into @OldID
End
Close C1
Close C2
Deallocate C1
Deallocate C2
Select * FRom @AuditTable