开发者

Why does my trigger always insert zero value in SQL Server?

开发者 https://www.devze.com 2023-02-18 01:26 出处:网络
I am rather confused, because my trigger in SQL Server cannot insert the value what I expected it would. The situation is as follows :

I am rather confused, because my trigger in SQL Server cannot insert the value what I expected it would. The situation is as follows :

  • I have transaction tab开发者_如何学Cle which can have two types of transactions in it - saldo and buy. If it is saldo, the trigger in transaction table will insert the amount of the transaction total to saldo table, but with Debit in its saldo_type field.

  • So if the case in transaction table is buy, the same amount will be inserted in saldo table, but with credit in its saldo_type field.

What confuses me is that the trigger will only insert the correct amount of value if the situation is saldo, but not if the situation is buy

What did I do wrong? Here is the code:

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 

Many Thanks!


Perhaps you can refactor your trigger to be a bit simpler:

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

Is the problem of zero solved with this code? If not, determine what @last_saldo and transaction_ammount values are. That'll lead you to the root of your problem.

Caveat: be aware that inserted can have more than one row!

0

精彩评论

暂无评论...
验证码 换一张
取 消