2012-03-13 97 views
-3
Table1 contains id(Auto PK), Key(Varchar) & Value(Int) 
Table2 contains Key(Varchar), postive_sum(Int), negative_sum(Int) 

我們需要寫一個觸發器每當一個新行插入表1複雜條件

  • 它應該比較新插入的值(newRow.Table1.Value)與前值( oldRow.Table1.Value)對於同一個密鑰

  • 如果是較大的,表2的positive_sum領域已 將通過與現有增值新插入的值(newRow.Table1.Value) 更新

  • 如果它較小,表2的negative_sum領域已 可以通過與現有值

  • 如果對錶2的鍵不存在,則相應的記錄添加新插入的值(newRow.Table1.Value) 更新必須創建

我們曾試圖與所需的邏輯,但我們沒有更多的在MS SQL Server 2008中

任何投入將不勝感激創建相同。

+0

所以,做的「鑰匙」已經存在於'Table2'?還是你必須先檢查表上的所有腦幹做一個'INSERT'然後一個'UPDATE'? – Lamak 2012-03-13 12:10:54

+0

什麼部分你不明白,或者你只是希望有人爲你寫一個完整的觸發器? – JeffO 2012-03-13 12:37:49

回答

0

注意:由於可能有更多的Table1記錄同時具有相同的密鑰更新,因此必須對這些差異進行求和,僅將彙總權重放在正面和負面的彙總字段中。試圖在沒有求和的情況下這樣做會失敗,因爲只有具有相同密鑰的最後一行將被記錄,其餘的將被丟棄。

alter trigger theTrigger on Table1 
after update, insert 
as 
    set NoCount ON 

    if update(Value) 
    begin 
     -- Add missing records to summary table 
     insert into table2 (Key, positive_sum, negative_sum) 
     select distinct Key, 0, 0 
      from Inserted 
      where not exists (select null from table2 t2 where t2.Key = Inserted.Key) 
     -- Update summary 
     update table2 
      set Positive_sum = isnull(positive_sum, 0) + isnull (diff.Positives, 0), 
       Negative_sum = isnull(Negative_sum, 0) + isnull (diff.Negatives, 0) 
      from table2 
     -- One can have only one record per key because otherwise sums would not be correct. 
      inner join (select Inserted.Key, 
          sum (case when Inserted.Value > isnull(Deleted.Value, 0) then Inserted.Value - isnull(Deleted.Value, 0) end) Positives, 
          sum (case when Inserted.Value < isnull(Deleted.Value, 0) then isnull(Deleted.Value, 0) - Inserted.Value end) Negatives, 
         from Inserted 
           left join Deleted on Inserted.ID = Deleted.ID 
         group by Inserted.Key 
         ) diff 
      on table2.Key = diff.Key 

    end