我很困惑,因为我的SQL Server中的触发器无法插入我所期望的值。这种情况如下:为什么我的触发器总是在SQL Server中插入零值?
我有
transaction
表,可以有两种类型的交易在里面 -saldo
和buy
。如果是saldo
,transaction
表中的触发器将把交易总额的金额插入到saldo
表中,但Debit
在其saldo_type
字段中。因此,如果
transaction
表的情况下是buy
,同样的金额将在其saldo_type
字段中插入saldo
表,但credit
。
什么让我困惑的是,触发只会插入的值正确的金额,如果情况是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
非常感谢!
好的,首先 - 它的拼写“数量”只有一个“m” - 你用两个“mm”拼写错误。第二:'Inserted'表可以容纳**多于一行** - 但是,您的代码只会在该“插入”列中假设一个条目 - 您需要修复该问题! – 2011-03-19 23:16:22
:)感谢您编辑错误输入的变量。实际上,代码是在印度尼西亚语中,所以在粘贴之前,我认为如果我翻译它会更好。非常感谢您指出! – swdev 2011-03-20 12:39:50