如何为此情况创建更新触发器

时间:2012-05-18 09:50:26

标签: sql-server-2008 triggers

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

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

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

2 个答案:

答案 0 :(得分:1)

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

您无法期望我们为您构建所有代码。

我会完全按照你在上一个问题上所做的那样,指出正确的方向。

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

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

答案 1 :(得分: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列,则更容易。并且还应该考虑数据类型..