SQL 服务器条件唯一约束 - 组合键
SQL server conditional unique constraint - Composite keys
我遇到一种情况,我需要对一组列强制执行唯一约束,但只针对列的一个值。假设有一个名为 Person 的 table 和列 'Name' 和 'isActive'
以下应该是结果
INSERT INTO Person (name,isActive) VALUES ('testUser1',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser1',1); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser1',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser1',1); --Failure
INSERT INTO Person (name,isActive) VALUES ('testUser1',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser2',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser2',1); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser2',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser2',1); --Failure
INSERT INTO Person (name,isActive) VALUES ('testUser2',0); --Success
基本上我需要的是相同的名称和 active=1 行不应该重复。
create unique index index_name on Person (name) where isActive = 1
我遇到一种情况,我需要对一组列强制执行唯一约束,但只针对列的一个值。假设有一个名为 Person 的 table 和列 'Name' 和 'isActive' 以下应该是结果
INSERT INTO Person (name,isActive) VALUES ('testUser1',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser1',1); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser1',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser1',1); --Failure
INSERT INTO Person (name,isActive) VALUES ('testUser1',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser2',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser2',1); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser2',0); --Success
INSERT INTO Person (name,isActive) VALUES ('testUser2',1); --Failure
INSERT INTO Person (name,isActive) VALUES ('testUser2',0); --Success
基本上我需要的是相同的名称和 active=1 行不应该重复。
create unique index index_name on Person (name) where isActive = 1