如何創建一個也允許空值的唯一約束? - How do I create a unique constraint that also allows nulls?

問題:

I want to have a unique constraint on a column which I am going to populate with GUIDs.我想對要填充 GUID 的列設置唯一約束。 However, my data contains null values for this columns.但是,我的數據包含此列的空值。 How do I create the constraint that allows multiple null values?如何創建允許多個空值的約束?

Here's an example scenario .這是一個示例場景 Consider this schema:考慮這個模式:

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)
)

Then see this code for what I'm trying to achieve:然後查看此代碼以瞭解我要實現的目標:

-- 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);

The final statement fails with a message:最後的語句失敗並顯示一條消息:

Violation of UNIQUE KEY constraint 'UQ_People_LibraryCardId'.違反 UNIQUE KEY 約束“UQ_People_LibraryCardId”。 Cannot insert duplicate key in object 'dbo.People'.無法在對象“dbo.People”中插入重複鍵。

How can I change my schema and/or uniqueness constraint so that it allows multiple NULL values, while still checking for uniqueness on actual data?如何更改我的架構和/或唯一性約束,使其允許多個NULL值,同時仍檢查實際數據的唯一性?


解決方案:

參考一: https://en.stackoom.com/question/3DhZ
參考二: https://stackoom.com/question/3DhZ
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章