如何为条件唯一值创建约束?

How to create a constraint for conditional unique values?

我正在使用 SQL 服务器。我有这个 table:

CREATE TABLE Student
(
   ID int PRIMARY KEY,
   FirstName varchar(100),
   LastName varchar(100),
   Active bit;
)

我只想在 Active = 1 时拥有 unique(FirstName, LastName) 学生。如果他们不活跃,则不应触发唯一约束。有什么想法吗?

创建过滤的唯一索引:

CREATE UNIQUE INDEX UNI_Student_FirstName_LastName ON Student (FirstName, LastName)
WHERE Active = 1

您不能为此创建 CONSTRAINT,但是,您 可以 创建过滤的唯一索引:

USE Sandbox;
GO

CREATE TABLE dbo.Student (ID int IDENTITY(1, 1) PRIMARY KEY,
                          FirstName varchar(100),
                          LastName varchar(100),
                          Active bit);


CREATE UNIQUE INDEX UQ_StudentName
    ON Student (FirstName,LastName)
    WHERE Active = 1;
GO

INSERT INTO dbo.Student (FirstName,
                         LastName,
                         Active)
VALUES ('Jane', 'Smith', 1); --Success
GO
INSERT INTO dbo.Student (FirstName,
                         LastName,
                         Active)
VALUES ('Jane', 'Smith', 0); --Success
GO
INSERT INTO dbo.Student (FirstName,
                         LastName,
                         Active)
VALUES ('Jane', 'Smith', 0); --Success
GO
INSERT INTO dbo.Student (FirstName,
                         LastName,
                         Active)
VALUES ('Jane', 'Smith', 1); --Fails;
GO

UPDATE dbo.Student
SET Active = 1
WHERE ID = 2; --Fails;
GO

SELECT *
FROM dbo.Student;
GO

DROP TABLE dbo.Student;

但是,我强烈反对名称唯一的想法。我(个人)在我年轻时的几个地方与另一个人分享了我的名字和出生日期,而在他们的系统中将名字(和出生日期)视为唯一的企业让我们俩都头疼(真的有我(或他们)不使用缩写名称就无法注册的地方,因为我们 "already existed").