2014-09-04 34 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