当从表中删除多行时,如何在删除触发器后处理

时间:2014-02-15 12:55:34

标签: sql-server triggers

我有两个表,一个表 bcdet 有交易详情,表二 accmast 有所有分类帐帐户的期末余额。当我尝试删除任何事务时,更新不起作用。

这是我的触发器代码。

ALTER trigger [dbo].[tr_ledgerdelete]
on [dbo].[BCDet]
after delete 
as
begin
    declare @dlcode int;
    declare @ddc nvarchar(2);
    declare @dAmt float;

    SET NOCOUNT ON;    

    set @ddc=(select dc from deleted)
    set @damt=(select amt from deleted)
    if (@ddc='C')
    begin
        update accmast set totcr=totcr-@damt where Lcode in (select Lcode from deleted)
        update accmast set clbal=totcr-totdr+opbal where Lcode in (select Lcode from deleted)
    end

    else

    begin
        update accmast set totdr=totdr-@damt where  Lcode in (select Lcode from deleted)
        update accmast set clbal=totcr-totdr+opbal where Lcode in (select Lcode from deleted)
    end

end

1 个答案:

答案 0 :(得分:0)

inserted和deleted表可以包含多行,因此不建议在触发器中使用变量。

此外,如果Lcode对于正在删除的事务不是唯一的,那么将其用作where谓词可能会允许您的更新触发太多行。

在不了解架构的情况下,很难说。这个样本应该克服第一个问题。

ALTER trigger [dbo].[tr_ledgerdelete]
on [dbo].[BCDet]
after delete 
as
begin
    SET NOCOUNT ON;    

    update t 
    set totcr = t.totcr - d.amt
    from accmast t 
    inner join deleted d on t.lcode = d.lcode
    where d.dc='C'

    update t 
    set totdr = t.totdr - d.amt
    from accmast t
    inner join deleted d on t.lcode = d.lcode
    where d.dc != 'C'

    update t 
    set clbal = t.totcr - t.totdr + t.opbal
    from accmast t
    inner join deleted d on t.lcode = d.lcode

end