MS SQL 检查两个字段是否重复
MS SQL Check for duplicate in two fields
我正在尝试创建一个触发器,根据他们的名字和姓氏的组合检查作者是否已经存在于 table 中。从我一直在阅读的内容来看,这个触发器应该可以工作,但是当我尝试将任何新作者插入 table 时,它会给出 "Author exists in table already!" 错误,即使我插入的作者在 table.
这是触发器
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
这是table
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]
如有任何帮助,我们将不胜感激!
您需要代替触发器来执行此操作。这也意味着您需要在触发器内部实际执行插入。沿着这些路线。
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
我正在尝试创建一个触发器,根据他们的名字和姓氏的组合检查作者是否已经存在于 table 中。从我一直在阅读的内容来看,这个触发器应该可以工作,但是当我尝试将任何新作者插入 table 时,它会给出 "Author exists in table already!" 错误,即使我插入的作者在 table.
这是触发器
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
这是table
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]
如有任何帮助,我们将不胜感激!
您需要代替触发器来执行此操作。这也意味着您需要在触发器内部实际执行插入。沿着这些路线。
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