java 创建唯一性约束_如何创建一个也允许空值的唯一约束? - 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? 如何创建允许多个空值的约束?

这是一个示例方案 。 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://stackoom.com/question/3DhZ/如何创建一个也允许空值的唯一约束

参考二:

https://oldbug.net/q/3DhZ/How-do-I-create-a-unique-constraint-that-also-allows-nulls

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值