SQL Server UNIQUE constraint with duplicate NULLs

2019-01-14 15:18发布

Possible Duplicate:
How do I create unique constraint that also allows nulls in sql server

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 constraint is no good in this situation because it considers NULL as regular values, so it will reject duplicate NULLs.

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

6条回答
Summer. ? 凉城
2楼-- · 2019-01-14 15:25

If you're using SQL Server 2008, have a look into Filtered Indexes to achieve what you want.

For older version of SQL Server, a possible alternative to a trigger involves a computed column:

  1. Create a computed column which uses the value of your "unique" column if it's not NULL, otherwise it uses the value of the row's Primary Key column (or any column which will be unique).
  2. Apply a UNIQUE constraint to the computed column.
查看更多
再贱就再见
3楼-- · 2019-01-14 15:29
虎瘦雄心在
4楼-- · 2019-01-14 15:33

You should use UNIQUEIDENTIFIER in that column, can be NULL and also is unique by definition. Hope that helps.

查看更多
干净又极端
5楼-- · 2019-01-14 15:34

You can create a view in which you select only not null values and create an index on it.

Here is the source - Creating Indexed Views

查看更多
时光不老,我们不散
6楼-- · 2019-01-14 15:45

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
查看更多
你好瞎i
7楼-- · 2019-01-14 15:48

Duplicate of this question?

The calculated column trick is widely known as a "nullbuster"; my notes credit Steve Kass:

CREATE TABLE dupNulls (
pk int identity(1,1) primary key,
X  int NULL,
nullbuster as (case when X is null then pk else 0 end),
CONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)
)

Works on SQL Server 2000. You may need ARITHABORT on e.g.

ALTER DATABASE MyDatabase SET ARITHABORT ON
查看更多
登录 后发表回答