2012-11-09 101 views
1

我在我的recharge表上創建了一個觸發器。它更新onaccountregistry表的餘額。有時SQL Server觸發器沒有觸發

但是,有時在將行插入到我的recharge表中時,它不會觸發觸發器。然後值不匹配。這個recharge表格每次插入行。

我按如下方式創建了觸發器。這不是一個複製的表格。我正在使用SQL Server 2008企業版。

請幫我解決這個問題

CREATE TRIGGER [dbo].[RechargeRefund] 
    ON [dbo].[ISRecharge] 
    FOR INSERT 
AS 
    declare @tin char(9) 
    declare @depocd char(1) 
    declare @oldvalue money 
    declare @newvalue money 
begin 
    select @tin = inserted.tin_subtin from inserted 
    select @depocd = inserted.updatetype from inserted 
    select @newvalue = inserted.DepositAmt from inserted 
    select @oldvalue = Totdeposit from ISOnAcctRegistry where tin_subtin = @tin 
end 

if @depocd ='1' 
begin 
    update ISOnAcctRegistry 
    set Totdeposit = @oldvalue + @newvalue 
    where tin_subtin = @tin 
end 

if @depocd ='2' 
begin 
    update ISOnAcctRegistry 
    set Totdeposit = @oldvalue - @newvalue 
    where tin_subtin = @tin 
end 
GO 

回答

2

嗯,當然,它不會工作 - 你假設每行觸發器觸發一旦插入

但這就是不是的情況。

觸發器觸發INSERT批次一次,僞表Inserted可能包含多行

如果您確實獲得了帶有多行的INSERT--您在哪裏選擇了哪條語句?

select @tin = inserted.tin_subtin from inserted 
select @depocd = inserted.updatetype from inserted 
select @newvalue = inserted.DepositAmt from inserted 
select @oldvalue = Totdeposit from ISOnAcctRegistry where tin_subtin = @tin 

你需要重寫你的扳機,這樣它會處理多行Inserted - 那麼它會工作每次。

+0

如何處理插入的多行請改變我的triger dear.please幫我做到這一點 – user1811342

+1

@ user1811342 - 如果你願意看看我昨天提供的答案,它顯示了觸發器應該如何寫入。 –

3

由於@marc指出,在寫作假設inserted單行是壞的 - 它甚至可以是可能的選擇3從inserted將值從3個不同的(任意)行從inserted分配到3個變量。

你可能想要的是:

update i1 
set Totdeposit = Totdesposit + t2.Total 
from ISOnAcctRegistry i1 
     inner join 
    (select 
     tin_subtin, 
     SUM(CASE updatetype 
       WHEN 1 THEN DepositAmt 
       WHEN 2 THEN -DepositAmt 
     ELSE 0 END) as Total 
     from inserted 
     group by tin_subtin) t2 
     on 
      i1.tin_subtin = t2.tin_subtin 

但你也許能建立在ISRecharge索引視圖替換此工作(在ISOnAcctRegistry此列) - 有一定的侷限性,你可以構建在ISRecharge中跨行自動執行SUM的視圖,並且SQL Server將負責爲您在後臺維護該值。

顯然,目前,您的觸發器不包含任何UPDATEDELETE活動ISRecharge。索引視圖會。