我想在要用GUID填充的列上具有唯一约束。但是,我的数据包含此列的空值。如何创建允许多个空值的约束?
这是一个示例方案。考虑以下模式:
CREATE TABLE People (
Id INT CONSTRAINT PK_MyTable PRIMARY KEY IDENTITY,
Name NVARCHAR(250) NOT NULL,
LibraryCardId UNIQUEIDENTIFIER NULL,
CONSTRAINT UQ_People_LibraryCardId UNIQUE (LibraryCardId)
)
然后查看此代码以了解我要实现的目标:
-- This works fine:
INSERT INTO People (Name, LibraryCardId)
VALUES ('John Doe', 'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA');
-- This also works fine, obviously:
INSERT INTO People (Name, LibraryCardId)
VALUES ('Marie Doe', 'BBBBBBBB-BBBB-BBBB-BBBB-BBBBBBBBBBBB');
-- This would *correctly* fail:
--INSERT INTO People (Name, LibraryCardId)
--VALUES ('John Doe the Second', 'AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA');
-- This works fine this one first time:
INSERT INTO People (Name, LibraryCardId)
VALUES ('Richard Roe', NULL);
-- THE PROBLEM: This fails even though I'd like to be able to do this:
INSERT INTO People (Name, LibraryCardId)
VALUES ('Marcus Roe', NULL);
最后一条语句失败,并显示一条消息:
违反UNIQUE KEY约束'UQ_People_LibraryCardId'。无法在对象“ dbo.People”中插入重复密钥。
如何更改架构和/或唯一性约束,使其允许多个NULL
值,同时仍检查实际数据的唯一性?
null
不是价值而是缺乏价值时。根据SQL标准,null
不视为null
。那么为什么倍数null
应该是唯一性违背呢?