在SQL Server 2012中触发以更新帐户余额

时间:2014-01-20 20:30:32

标签: sql-server triggers

我有一个CustomerMaster表,其中有一个名为AccountBalance的列。每个客户(由CustomerMaster中的CustomerId唯一标识)可以在ClientTransaction表中具有0,1或多个事务,该表具有名为Amount的列(指示事务量)。我想在ClientTransaction表上为INSERT,UPDATE和DELETE创建一个触发器来维护AccountBalance。我尝试过定义下面的触发器;当我只删除一行时,它会正确更新AccountBalance;但是,当我执行DELETE ClientTransaction删除所有记录时,它不起作用。有什么想法吗?

CREATE TRIGGER [dbo].[ClientAccountBalanceUpdate]
   ON  [dbo].[ClientTransaction]
   FOR INSERT,DELETE,UPDATE
AS  
BEGIN
    SET NOCOUNT ON;

    if not exists (select 1 from Inserted) -- Delete trigger
        update CustomerMaster set AccountBalance = AccountBalance - D.Amount from CustomerMaster inner join Deleted D on CustomerMaster.CustomerId = D.CustomerId 

    if not exists (select 1 from Deleted) -- Insert Trigger
        update CustomerMaster set AccountBalance = AccountBalance + I.Amount from CustomerMaster inner join Inserted I on CustomerMaster.CustomerId = I.CustomerId

    if  exists (select 1 from Deleted) and exists (select 1 from Inserted) -- Update trigger
        update CustomerMaster set AccountBalance = AccountBalance - D.Amount + I.Amount from CustomerMaster inner join Inserted I on CustomerMaster.CustomerId = I.CustomerId inner join Deleted D on CustomerMaster.CustomerId = D.CustomerId

END

2 个答案:

答案 0 :(得分:1)

正如评论中所述,您的问题是您的代码仅在有一个交易时才有效。下面是您的代码在插入中处理多行的示例。

If Not Exists (Select 1 From Deleted) -- Insert Trigger
    Update CustomerMaster 
    Set AccountBalance = AccountBalance + 
        (
        Select Sum(I.Amount)
        From Inserted I 
        Where CustomerMaster.CustomerId = I.CustomerId
        )
    From CustomerMaster 

答案 1 :(得分:0)

您的触发器仅触发一次(插入,更新或删除第一行时)。

如果您insertdeleteupdate超过1行,则下次不会触发您的触发器,除非满足下2个条件(按给定顺序):< / p>

  1. 所有队列(已插入,已删除和已更新)已清空
  2. 插入,删除和更新后全部为空,插入,删除或更新另一行。