2014-09-04 77 views
1

我有我的數據庫中的觸發器,防止進入一個特定的用戶,並停止用戶進入同一個問題兩次:不是插入的觸發器不執行if語句corectly

create trigger [dbo].[question] 
on [dbo].[Online_Questions] 
instead of insert 
as 
if SYSTEM_USER = 'John' 
begin 
raiserror('You have not paid up your fee',16,1) 
rollback transaction 
end 
if exists(select 1 
    from Online_Questions a, inserted b where a.UserName = b.UserName 
    and a.Question_ID = b.Question_ID) 
begin 
raiserror('You have already submitted this question',16,1) 
rollback 
end 
go 

它成功地阻止約翰進入,但是無論Question_ID如何,它都會阻止任何人進入兩次。

例如:

execute as login = 'Tom'; 

insert into Online_Questions (UserName, Question_ID, Answer) 
values (user, 'Q097', 'D'); 

,然後作爲觸發已經阻止了插入件

insert into Online_Questions (UserName, Question_ID, Answer) 
values (user, 'Q087', 'D'); 

將返回一個錯誤。

我不明白爲什麼這是因爲if語句檢查是否存在用戶名和question_ID?

有什麼建議嗎?

+0

嘗試更改此觸發器後觸發器,幾周前我有這樣的問題,但我不記得確切的問題。由於您在統計數據中使用了回滾,所以觸發後不會出現問題。 – FpontoDesenv 2014-09-04 01:32:44

+0

@FpontoDesenv我必須使用插入觸發器(這是一個要求),所以不幸的是我不能嘗試一個觸發器 – James 2014-09-04 02:10:48

+0

@AaronBertrand我認爲我已經在查看這個時,我正在匹配插入的值已經在那些桌子? – James 2014-09-04 02:14:42

回答

0

我已經知道我要出錯的地方,它的格式不正確,看着兩張表。這是解決方案。

create trigger [dbo].[question] 
on [dbo].[Online_Questions] 
instead of insert 
as 
if SYSTEM_USER = 'John' 
begin 
raiserror('You have not paid up your fee',16,1) 
return 
end 
if (not exists (select oq.UserName, oq.Question_ID from Online_Questions oq, inserted i where oq.UserName = i.UserName and oq.Question_ID = i.Question_ID)) 
begin 
insert into Online_Questions 
select User, Question_ID, Answer 
from inserted 
end 
else 
begin 
raiserror('You have already submitted this question',16,1) 
end 
go