为什么我的触发器总是在SQL Server中插入零值?

时间:2011-03-19 17:05:36

标签: sql-server

我很困惑,因为我在SQL Server中的触发器无法插入我期望的值。情况如下:

  • 我有transaction表,其中可以包含两种类型的交易 - saldobuy。如果是saldo,则transaction表中的触发器会将事务总计的金额插入saldo表,但Debit字段中会显示saldo_type

  • 因此,如果transaction表中的案例为buy,则会在saldo表格中插入相同的金额,但credit中的saldo_type }} field。

让我感到困惑的是,如果情况为saldo,触发器只会插入正确数量的值,但如果情况为buy

则不会

我做错了什么?这是代码:

declare @last_saldo int
declare @transaction_ammount int

set @last_saldo = (select sum(saldo_ammount) from saldo)
if @last_saldo is null set @last_saldo=0

set @transaction_ammount = (select transaction_ammount from inserted)
IF (select transaction_type from inserted) = 'Saldo'
begin
/* this will insert correct amount */
INSERT INTO saldo
    (id_transaction,transaction_type,saldo_ammount,saldo)
SELECT id_transaction,'Debit',@transaction_ammount,@last_saldo + @transaction_ammount
FROM inserted
RETURN 
END else IF (select transaction_type from inserted)='Buy'
begin
    /* this will not insert the correct ammount. It will always zero! */
INSERT INTO saldo
    (id_transaction,transaction_type,saldo_ammount,saldo)
SELECT id_transaction,'Credit',@transction_ammount,(@last_saldo - @transaction_ammount)
FROM inserted
RETURN 
END 

非常感谢!

1 个答案:

答案 0 :(得分:1)

也许你可以重构你的触发器,使其更简单:

declare @last_saldo int

select @last_saldo = ISNULL(sum(saldo_ammount),0)
 from saldo

INSERT INTO saldo
        (id_transaction,transaction_type,saldo_ammount,saldo)

    SELECT id_transaction,
           CASE WHEN transaction_type = 'Saldo' 
             THEN 'Debit'
             ELSE 'Credit' 
           END,
           transaction_ammount,
           CASE WHEN transaction_type = 'Saldo' 
             THEN (@last_saldo + transaction_ammount)
             ELSE (@last_saldo - transaction_ammount)
           END
    FROM inserted
RETURN

此代码是否解决了零问题?如果不是,请确定@last_saldotransaction_ammount值是什么。这会引导你找到问题的根源。

警告:请注意inserted可以有多行!