2013-04-06 47 views
2
create table test3 
(
id int PRIMARY KEY, 
id2 int 
); 

create unique index ndx_id2 on test3 (id2); 

为唯一指标的目的,进入了很多空值,所有的NULL值从所有其他NULL值视为不同,因此独特。这是对SQL-92标准的两种可能的解释之一(标准中的语言是不明确的),PostgreSQL,MySQL,Firebird和Oracle的解释是其中之一。如何允许在该领域具有唯一约束在SQL Server

Informix和Microsoft SQL Server遵循标准的其他解释。

INSERT INTO test3(id, id2) VALUES (1, null); 
INSERT INTO test3(id, id2) VALUES (2, null); 

第二插入返回

重复的值不能被插入到一个唯一索引。 [表名 = TEST3,约束名称= ndx_id2]

错误SQL Server,但成功地增加了记录到其他的DBMS,SQLite的例如。

如何允许在字段中使用唯一约束在SQL Server中输入大量空值?

回答

7

从SQL Server 2008及以后,你可以使用一个filtered index

create unique index UX_YourIndex 
on YourTable(col1) 
where col1 is not null 

Example at SQL Fiddle.

对于SQL Server 2005及以上(9.0 corresponds to 2005),你可以使用一个代理列。代理列是计算列。它被计算如下:

  • 当半唯一的列是不null,替代列等于该列
  • 当半唯一的列是null,替代列等于一个独特ID。唯一的ID可以是标识列,rowguid或每行不同的任何内容。

换句话说,只要原始列是null,代理列就会使用唯一的字符串。例如:

create table YourTable 
    (
    id int identity primary key 
, col1 int 
, surrogate1 as (coalesce(convert(varchar(20), col1), '_' + convert(varchar(20), id))) 
    ); 

create unique index UX_YourIndex on YourTable(surrogate1); 

确保代理值不会与实际值相冲突是您的工作。在这个例子中,我假设col1不能以下划线开头。

Example at SQL Fiddle.

+0

您的脚本不允许为空值。相反,我需要添加很多空值。示例:1,2,null,null,null,null,3. – user2217261 2013-04-06 15:32:39

+0

您应该被允许插入多个空值 - 请参见[SQL Fiddle]上的示例(http://sqlfiddle.com/#!6/dbf85/ 1/0) – Andomar 2013-04-06 17:44:09

+0

@ user2217261:[Works for me](http://sqlfiddle.com/#!3/fa6dc/3)。 – 2013-04-06 17:44:21