2013-04-06 46 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