具有重复NULL的SQL Server UNIQUE约束 [英] SQL Server UNIQUE constraint with duplicate NULLs

查看:157
本文介绍了具有重复NULL的SQL Server UNIQUE约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何创建唯一约束,允许在sql server中使用空值

我有一个表格,我需要强制列具有唯一值。
此列必须是可空的,并且应该允许业务逻辑使用多个NULL值,而其他重复值则不允许。

I have a table where I need to force a column to have unique values. This column must be nullable and by business logic multiple NULL values should be permitted, whereas other duplicate values are not.

SQL Server UNIQUE约束无效这种情况,因为它将NULL视为常规值,因此它将拒绝重复的NULL。

SQL Server UNIQUE constraint is no good in this situation because it considers NULL as regular values, so it will reject duplicate NULLs.

目前,BLL授予了值唯一性,所以我不是在寻找脏破解使它工作。
我只是想知道是否有一个干净的解决方案来强制执行数据库中的约束。

Currently, value uniqueness is granted by the BLL so I'm not looking for a dirty hack to make it work. I just would like to know if there is a clean solution to enforce this constraint in the DB.

是的,我知道我可以写一个触发器那样做:触发器是唯一的解决方案吗? (或者最好的解决方案呢?)

And yeah, I know I can write a trigger to do that: is a trigger the only solution? (or the best solution anyway?)

推荐答案

如果您使用的是SQL Server 2008(不适用于早期版本)有过滤索引的概念。您可以在表的已过滤子集上创建索引。

If you're using SQL Server 2008 (won't work for earlier version) there is the concept of a filtered index. You can create the index on a filtered subset of the table.

CREATE UNIQUE INDEX indexName ON tableName(columns) INCLUDE includeColumns 
WHERE columnName IS NOT NULL

这篇关于具有重复NULL的SQL Server UNIQUE约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆