我很困惑,因爲我的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