2010-09-28 44 views

回答

1

到SQL Server 2000上的作品,后来筛选的索引的替代方案是一个indexed view.

喜欢的东西:

CREATE VIEW DRI_YourTable_NonNullUnique 
WITH SCHEMABINDING 
AS 
    SELECT YourColumn FROM dbo.YourTable WHERE not YourColumn is NULL 
GO 
CREATE UNIQUE CLUSTERED INDEX IX_DRI_YourTable on DRI_YourTable_NonNullUnique (YourColumn) 

请注意,你不这样做一旦创建了这个视图,必须做任何特别的事情 - 你不需要再次引用它。如果试图在基表中插入非唯一值,它只会导致发生约束违规。

@marc_s - 我不同意。他们肯定不会在下面Enterprise版本自动视为(查询编译),但他们绝对可创建和工作的DRI执法中的所有版本:

select @@VERSION 

create table dbo.T1 (
    T1ID int IDENTITY(1,1) not null, 
    Val1 varchar(10) null, 
    constraint PK_T1 PRIMARY KEY (T1ID) 
) 
go 
create view dbo.DRI_T1_Val1Unique 
with schemabinding 
as 
    select Val1 from dbo.T1 where Val1 is not null 
go 
create unique clustered index IX_DRI_T1_Val1Unique on dbo.DRI_T1_Val1Unique (Val1) 
go 
insert into dbo.T1 (Val1) 
select 'abc' union all 
select null union all 
select null 
go 
insert into dbo.T1 (Val1) 
select 'abc' 
go 
select * from dbo.T1 

结果:

Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) May 3 2005 23:18:38 Copyright (c) 1988-2003 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2) 

1 abc 
2 NULL 
3 NULL 

而且:

(1 row(s) affected) 

(3 row(s) affected) 
Msg 2601, Level 14, State 3, Line 1 
Cannot insert duplicate key row in object 'DRI_T1_Val1Unique' with unique index 'IX_DRI_T1_Val1Unique'. 
The statement has been terminated. 

(0 row(s) affected) 

(3 row(s) affected) 
+0

但索引视图仅在企业版本中可用 - 在Express,Workgroup或Standard版本中无法使用:-( – 2010-09-28 06:49:05

1

不幸的是,你不能在SQL Server 2005中做到这一点。唯一索引只允许一行NULL值。

使用SQL Server 2008,您可以使用已过滤索引 - 仅在部分行上定义的索引,例如,那些不是空的。这是一个2008年的功能,所以你将不能够做到这一点在2005年

CREATE UNIQUE NONCLUSTERED INDEX IX_UNIQUE 
ON dbo.YourTable(YourColumn) 
WHERE YourColumn IS NOT NULL 
GO 

参见:

0

你不能让一个可空列通过该列上的常规唯一约束唯一,但是您可以通过基于函数的索引实现该约束,不知道这样的构造是否存在于sql服务器b上UT可能解决它在Oracle数据库上

相关问题