2012-11-09 2 views
1

recharge 테이블에 트리거가 생성되었습니다. onaccountregistry 테이블의 잔액을 업데이트합니다.가끔 SQL Server 트리거가 실행되지 않습니다.

가끔 내 recharge 테이블에 행을 삽입 할 때 트리거가 실행되지 않습니다. 그런 다음 값이 일치하지 않습니다. 이 recharge 테이블은 매번 행을 삽입합니다.

다음과 같이 트리거를 생성했습니다. 이것은 복제 된 테이블이 아닙니다. SQL Server 2008 Enterprise Edition을 사용하고 있습니다.

날이 문제

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을 얻은 경우 여기에서 귀하의 명세서가 어떤 행을 선택합니까? 그 때마다 일 것이다 - 그것은Inserted여러 행을 처리 할 수 ​​있도록

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 

당신은 트리거를 다시 작성해야합니다. @marc 지적한 바와

+0

삽입 된 여러 행을 어떻게 처리 할 수 ​​있습니까? triger dear.please를 변경하면 도움이됩니다. – user1811342

+1

@ user1811342 - 어제 제공되는 답변을 보길 원한다면 트리거를 작성하는 방법을 보여줍니다. –

3

inserted 단일 행 가정 쓰는 것은 나쁜 - 심지어 inserted 3 상이한 (임의의) 행에서 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에서이 열을) 대체 할 수 있습니다 - 일부 제한, 당신은 빌드 :

당신이 아마 원하는 것은 행에 걸쳐 SUM을 자동으로 수행하는보기가 ISRecharge이고 SQL Server는 백그라운드에서 값을 유지 관리해야합니다.

분명히 현재 귀하의 방아쇠는 또는 DELETE의 활동을 ISRecharge에 대해 설명하지 않습니다. 인덱싱 된 뷰.

관련 문제