我需要监控表上的字段子集,并在其中一个字段发生更改时执行任务。
我在表更新时使用触发器,然后查看更改,如下所示:
-- join the deleted and inserted to get a full list of rows
select * into #tmp from (select * from inserted union select * from deleted) un
-- select a count of differing rows, > 1 means something is different
select distinct count(*) from #tmp
这很好,计数为2或更多意味着单行更新有所不同。问题是,如果我正在进行多行更新,那么这会破坏。
我有没有办法让这个可以用于多行更新,或者我是否需要完全尝试不同的方法。
答案 0 :(得分:1)
你可以这样做(语法完全未经测试)
IF NOT UPDATE(col)
RETURN
SELECT inserted.key, inserted.col as i_col, deleted.col as d_col
INTO #interestingrows
FROM inserted JOIN deleted on inserted.key = deleted.key
and inserted.col <> deleted.col /*If col is nullable cater for that as well*/
IF @@ROWCOUNT=0
RETURN
/*Process contents of #interestingrows*/
答案 1 :(得分:-1)
我最终找到了一个相当简单的解决方案。我在检查中写了一个额外的循环,它在插入的每行检查。
-- get a list of updated line id's
select field1 as id into #loop from inserted
-- loop through all the id's and do a compare
while (select count(*) from #loop) > 0 begin
select top 1 @id = id from #loop
select * into #tmp from (select * from inserted where field1 = @id union
select * from deleted where field1 = @id) un
-- do a select ditinct to count the differing lines.
if (select distinct count(*) from #tmp) > 1 begin
-- the 2 lines don't match, so mark for update
update test1 set flag = 1 where field1 = @id
end
drop table #tmp
delete #loop where id = @id
end