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
transactiontable which can have two types of transactions in it –saldoandbuy. If it issaldo, the trigger intransactiontable will insert the amount of the transaction total tosaldotable, but withDebitin itssaldo_typefield. -
So if the case in
transactiontable isbuy, the same amount will be inserted insaldotable, but withcreditin itssaldo_typefield.
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:
Is the problem of zero solved with this code? If not, determine what
@last_saldoandtransaction_ammountvalues are. That’ll lead you to the root of your problem.Caveat: be aware that
insertedcan have more than one row!