2012-03-13 99 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