我很困惑,因为我在SQL Server中的触发器无法插入我期望的值。情况如下:
我有transaction
表,其中可以包含两种类型的交易 - saldo
和buy
。如果是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
非常感谢!
答案 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_saldo
和transaction_ammount
值是什么。这会引导你找到问题的根源。
警告:请注意inserted
可以有多行!