我正在尝试创建一个触发器,该触发器将根据其姓氏和名字的组合检查作者是否已存在于表中。从我一直在阅读这个触发器应该工作,但当我尝试将任何新作者插入表中时,它给出了“作者已存在于表中!”即使我正在插入表中不存在的作者,也会出错。
这是触发器
USE [WebsiteDB]
GO
CREATE TRIGGER [dbo].[tr_AuthorExists] ON [dbo].[Authors]
AFTER INSERT
AS
if exists ( select * from Authors
inner join inserted i on i.author_fname=Authors.author_fname AND i.author_lname=Authors.author_lname)
begin
rollback
RAISERROR ('Author exists in table already!', 16, 1);
End
这是表格
CREATE TABLE [dbo].[Authors](
[author_id] [int] IDENTITY(1,1) NOT NULL,
[author_fname] [nvarchar](50) NOT NULL,
[author_lname] [nvarchar](50) NOT NULL,
[author_middle] [nvarchar](50) NULL,
CONSTRAINT [PK_Authors] PRIMARY KEY CLUSTERED
(
[author_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
任何帮助都将不胜感激!
答案 0 :(得分:1)
您需要将此作为INSTEAD触发器。这也意味着您需要在触发器内实际执行插入。这些方面的东西。
CREATE TRIGGER [dbo].[tr_AuthorExists] ON [dbo].[Authors]
instead of insert
AS
set nocount on;
if exists
(
select * from Authors a
inner join inserted i on i.author_fname = a.author_fname AND i.author_lname = a.author_lname
)
begin
rollback
RAISERROR ('Author exists in table already!', 16, 1);
End
else
insert Authors
select i.author_fname
, i.author_lname
, i.author_middle
from inserted i