-1

我想写一个存储过程(SQL server 2008r2),假设我有一个表:

人

列:
Id int (pk)
Date_of_birth 日期不为空
电话 int 允许 null
地址 int 允许 null
名称 nvarchat(50) 不为空

样本数据: Id=1,Date_of_birth=01/01/1987,phone=88888888,address=null,name='Steve'

存储过程中的更新语句,假设参数已经声明: Update person set Date_of_birth=@dob,phone=@phone,address=@address,name=@name where id=@id

该表有一个触发器来记录任何更改。现在我有一个用于更新上述人员表的 asp.net 更新页面

问题是,如果用户只想更新 address='apple street' ,上面的更新语句将更新所有字段但不检查原始值是否=新值,然后忽略该字段然后检查下一个字段。所以我的日志表将记录所有事件,即使列不会被更新。

在这一点上,我的解决方案

  1. 通过 id 选择所有值并将它们存储到局部变量中。使用 if-else 检查并生成更新语句。最后动态运行生成的SQL(sp_executesql)
  2. 通过 id 选择所有值并将它们存储到局部变量中。使用 if-else 分别检查和更新每个字段:

If @dob <> @ori_dob
Begin
Update person set date_of_birth=@dob where id=@id
End

可能这是一个愚蠢的问题,但如果您有更好的想法,请告诉我,谢谢!

4

1 回答 1

0

This is an answer to a comment by the OP and does not address the original question. It would, however, be a rather ugly comment.

You can use a statement like this to find the changes to Address within an UPDATE trigger:

select i.Id, d.Address as OldAddress, i.Address as NewAddress
  from inserted as i inner join
    deleted as d on d.Id = i.Id
  where d.Address <> i.Address

One such statement would be needed for each column that you want to log.

You could accumulate the results of the SELECTs into a single table variable, then summarize the results for each Id. Or you can use INSERT/SELECT to save the results directly to your log table.

于 2012-07-17T13:07:42.633 回答