我的数据库触发器阻止特定用户输入并阻止用户输入两次相同的问题:
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
它成功阻止John进入,但无论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 :(得分: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