问题描述
可能的重复:
如何创建唯一约束这也允许 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 约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)