2011-03-19 25 views
1

我很困惑,因爲我的SQL Server中的觸發器無法插入我所期望的值。這種情況如下:爲什麼我的觸發器總是在SQL Server中插入零值?

  • 我有transaction表,可以有兩種類型的交易在裏面 - saldobuy。如果是saldotransaction表中的觸發器將把交易總額的金額插入到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 

非常感謝!

+1

好的,首先 - 它的拼寫「數量」只有一個「m」 - 你用兩個「mm」拼寫錯誤。第二:'Inserted'表可以容納**多於一行** - 但是,您的代碼只會在該「插入」列中假設一個條目 - 您需要修復該問題! – 2011-03-19 23:16:22

+1

:)感謝您編輯錯誤輸入的變量。實際上,代碼是在印度尼西亞語中,所以在粘貼之前,我認爲如果我翻譯它會更好。非常感謝您指出! – swdev 2011-03-20 12:39:50

回答

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_saldotransaction_ammount的值。這會將你引向問題的根源。

注意:請注意,inserted可以有多行!

+0

:)非常感謝重寫我的觸發器。這是我第一次使用MS SQL觸發器,我之前用My SQL做觸發器。我在這裏應用你的觸發器,結果是一樣的。但是,在我檢查代碼後,事實證明,我爲事務ammount插入0,但後來我將它更新爲正確的ammount。因爲我的觸發器只處理INSERT,所以......你知道發生的錯誤...... :) 非常感謝。我接受了這個答案,並且通過比較我的第一個觸發器和你的觸發器代碼,我學到了很多東西。完善! – swdev 2011-03-20 12:44:55

+0

我只知道插入的可以有多行。如果是這樣的話,爲了使觸發器符合要求,修改將會是什麼?謝謝 – swdev 2011-03-20 15:47:15

+0

@swdev:這個解決方案似乎很好地處理了多行,並且在這個答案結尾處的「插入」中的多行警告只是意味着爲你提供一般提醒。也就是說,每次在SQL Server中編寫觸發器時,請記住始終將'魔術'表'插入'和'刪除'視爲具有多行。 – 2011-03-20 19:24:22