2012-12-16 3 views
0

트리거가 있습니다. 이름이 같은 장비 (항상 하나의 요소)가 이미 테이블에 있으면 롤백해야합니다. 그러나 항상 such equipment already exist 메시지로 트랜잭션을 롤백합니다. 장비가 테이블에있을 때와 없을 때. 문제가 무엇입니까?트리거는 항상 트랜잭션을 롤백합니다.

CREATE trigger [dbo].[ut_TEquipment] 
on [dbo].[TEquipment] 
for insert 
as 
begin 

declare @var nvarchar(30) 
select @var = name from inserted 
print @var 

if (@var in (select name from TEquipment)) 
begin 
    raiserror('Such equipment already exist',10,1) 
    rollback transaction 
end 

declare @amount int 
declare @free int 

select @amount = x.amount from inserted as x 

select @free = y.free from TEquipWarehouse as y,inserted as x 
where y.ideqwhs = x.ideqwhs 

if (@free - @amount) <= 0 
begin 
raiserror('Free space in this warehouse is not enough!',10,1) 
rollback transaction 
end 
else 
begin 
update TEquipWarehouse 
set free = capacity - amount 
from inserted as x 
    where idwhstype = x.ideqwhs 
end 

end 

답변

2

FOR으로 정의 된 트리거는 그 원인이되는 SQL 이후에 발생합니다. 따라서 트랜잭션의 관점에서 행은 이미 테이블에 있습니다. 트리거를 통해이를 수행하려면 INSTEAD OF을 사용해야합니다. 그러나 이름 열에 UNIQUE 제약 조건을 정의하는 것이 훨씬 쉬울 것입니다.

또한 삽입 트리거가 inserted 테이블에 여러 행을 가질 수 있다고 생각해야합니다. 예를 들어 :

http://sqlfiddle.com/#!6/7d51d/1

:

Insert Into TEquipment (Name) Values (N'Test'), (N'Test'); 

는 두 행 다음

an example 당신이 뭔가를 할 거라고 트리거를 사용하여이 FOR하려면 다른 트리거 behavoiurs

을 보여주는 쇼 것

비록 여러 개의 동시 트랜잭션을 처리 할 것인지 확신하지 못합니다.

관련 문제