0

假设我有一个表 ABC 和表 XYZ。

Columns of ABC-->col1 col2 col3 col4 ......coln
Columns of XYZ-->colname oldvalue newvalue modifieddate

因此,当列,假设 col1 在 ABC 中更新时,我希望我的 XYZ 应该能够插入一条记录,该记录具有正在修改的列的名称、该列的旧值、该列的新值和修改日期。因此,对于在 ABC 中修改的每一列,我应该在 XYZ 中获得记录,任何人都可以帮我从这个开始,是否可以首先,欢迎任何建议,谢谢

4

2 回答 2

1

你刚刚问了一个关于触发器的问题。

您不能指望我们为您构建所有代码。

我会完全按照您上一个问题所做的那样做,并为您指明正确的方向。

要知道列是否已更新,您可以使用 UPDATE(column) 关键字

create trigger logUpdate
on ABC
After update
as
begin
  if (update(col1)) begin
    --will only get in here if the col1 was referenced on the update statment
     insert into XYZ based ont INSERTED and DELETED tables
  end
end

编辑:替代方案:CDC

于 2012-05-18T09:59:42.673 回答
1

在触发器中,我会为每个列写这样的内容:

Select 'Col1' ColumnName, i.Col1 NewValue, d.Col1 OldValue
From Inserted i 
    Inner Join Deleted d On i.IDCol = d.IDCol
Where 
    (i.Col1 Is Null and Not d.Col1 is Null)
    OR (Not i.Col1 Is Null and d.Col1 is Null)
    OR (Not i.Col1 is Null And Not d.Col1 Is Null AND i.Col1 != d.Col1)

在这种情况下,如果在一个语句中更新了很多行,它将考虑到只有在数据发生更改时才会记录更改。

如果有 NOT NULL 列,它会更容易。并且还应该考虑数据类型..

于 2012-05-18T10:17:29.250 回答