2010-08-16 79 views
1

我需要監控表格上的字段子集,並在其中一個變化時執行任務。檢查觸發器中是否發生了變化

我使用它,然後在看變動情況如下表更新觸發:

-- 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種或更多的手段計數是單行更新不同。問題是如果我正在做一個多行更新,那麼這個失敗。

有沒有一種方法可以讓我爲多行更新工作,還是我需要完全嘗試不同的方法。

回答

-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 
+0

這是行不通的。 '選擇不同的計數(*)'不符合你的想法。例如(*)AS D,COUNT(DISTINCT x)AS X FROM cte' – 2010-08-17 08:51:15

+0

-1。請嘗試使用cte AS(SELECT 1 AS x UNION ALL SELECT 1)SELECT DISTINCT COUNT這是行不通的 – Fandango68 2014-02-18 05:58:01

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*/ 
相關問題