【问题标题】:Complex Condition in Database Trigger数据库触发器中的复杂条件
【发布时间】:2012-03-13 12:03:24
【问题描述】:
Table1 contains id(Auto PK), Key(Varchar) & Value(Int)
Table2 contains Key(Varchar), postive_sum(Int), negative_sum(Int)

每当在 Table1 中插入新行时,我们都需要编写触发器

  • 它应该将新插入的值(newRow.Table1.Value)与相同Key的先前值(oldRow.Table1.Value)进行比较

  • 如果大于,Table2的positive_sum字段有 通过添加新插入的值来更新(newRow.Table1.Value) 现有价值

  • 如果更小,Table2的negative_sum字段有 通过添加新插入的值来更新(newRow.Table1.Value) 现有价值

  • 如果table2上的key不存在,则必须创建对应的记录

我们已经尝试了所需的逻辑,但我们在 MS SQL Server 2008 中创建相同的逻辑方面缺乏更多。

任何意见将不胜感激。

【问题讨论】:

  • 那么,Table2 上是否已经存在“密钥”?还是必须先检查该表上的存在性才能执行INSERT,然后再执行UPDATE
  • 你不明白哪一部分,或者你只是希望有人为你写一个完整的触发器?

标签: sql-server database triggers


【解决方案1】:

注意:由于可能有更多的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    相关资源
    最近更新 更多