SQL Server 2005 具有空值的唯一键
我在 SQL Server 2005 中有一个带有外键的表,并且我希望该外键为唯一值或 null。我已将其设置为唯一键,但它不允许我在同一个表中有多个空值。可以做我想做的事吗?
I have a table in SQL Server 2005 with a foreign key, and I want that foreign key to be a unique value or null. I've set it up as a unique key, but it won't allow me to have multiple nulls in the same table. Is it possible to do what I want?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是对 SQL Server 的唯一约束/索引的长期抱怨。最好的解决方案是创建一个具有模式绑定的视图,然后在该列上放置唯一索引:
This is a long time complaint about SQL Server's Unique constraints/indexes. The best solution is to create a view with schemabinding and then put a unique index on that column:
您无法在 SQL Server 2005 中使用表级约束来强制执行此操作,但您可以使用定义 SELECT Col FROM t WHERE Col IS NOT NULL 创建一个视图,然后在其上创建唯一的聚集索引。
You cannot enforce this with a table level constraint in SQL Server 2005 but you can create a view with definition
SELECT Col FROM t WHERE Col IS NOT NULL
and then create a unique clustered index on that.在 SQL Server 2008 中,您可以创建过滤索引非空值 - 不幸的是,这是 2008 版本中的新功能,所以2005年,恐怕你做不到这样的事情。
In SQL Server 2008, you could create a filtered index on the values that are not null - unfortunately, that is a new feature in the 2008 release, so in 2005, you're not able to do anything like that, I'm afraid.
一直是我的烦恼。我更喜欢该标准的“其他”解释。
请参阅创建唯一SQL Server 中忽略空值的约束。它涵盖了三种不同的方法。
解决方案 1:过滤索引。
从其他回复来看,这似乎很常见。我还没有尝试过这种方法 - 但它需要 SQL Server 2008。
解决方案 2:对计算列进行约束
这个我用过,确实有效。但是,可能需要调整关系和/或添加辅助非唯一覆盖索引(一个用于唯一约束,一个用于索引覆盖)。
解决方案3:UDF检查约束(不推荐)
啊,TSQL 的强大功能(请阅读:需要处理其他的事情)。我没有走这条路。
快乐编码。
Always an annoyance of mine. I prefer the "other" interpretation of the standard.
See Creating a unique constraint that ignores nulls in SQL Server. It covers three different approaches.
Solution 1: Filtered indexes.
This seems pretty common, judging from other replies. I have not tried this approach -- it does require SQL Server 2008 though.
Solution 2: Constraint on computed column
I have used this, and it does work. However, relationships may need to be adjusted and/or secondary non-unique covering indexed added (one for unique constraint, one for index cover).
Solution 3: UDF Check Constraint (Not recommended)
Ahh, the power of TSQL (read: something else to deal with). I have not gone down this route.
Happy coding.