TSQL多列唯一约束,也允许多个空值

Ant*_*ggs 4 sql t-sql sql-server sql-server-2008 filtered-index

我目前正在从MS Access迁移到SQL Server.由于Access允许在唯一索引上有多个Null,而SQL Server没有......我一直在通过删除SQL Server中的索引并添加过滤索引来处理迁移:CREATE UNIQUE NONCLUSTERED INDEX idx_col1_notnull ON tblEmployee(col1) WHERE col1 IS NOT NULL;

我遇到的问题是我不确定如何实现复合或多列"过滤"索引...或者如果这是真的可能,因为我没有找到研究它的例子.

我有一个想法,通过创建过滤索引来实现它,如下所示:

CREATE UNIQUE NONCLUSTERED INDEX idx_col1col2_notnull ON tblEmployee(col1,col2) WHERE col1 IS NOT NULL
Run Code Online (Sandbox Code Playgroud)

然后添加第二个过滤索引:

CREATE UNIQUE NONCLUSTERED INDEX idx_col2col1_notnull ON tblEmployee(col1,col2) WHERE col2 IS NOT NULL
Run Code Online (Sandbox Code Playgroud)

但我不确定这是否会起作用,更不用说是最好的方法了.我们将非常感谢正确方向的指导.

Gio*_*uri 7

您可以添加以下索引以仅索引不可为空的列:

create table tblEmployee(col1 int, col2 int)
go

create unique nonclustered index idx_col1col2_notnull ON tblEmployee(col1,col2) 
where col1 is not null and col2 is not null
go

--This Insert successeds
insert into tblEmployee values
(null, null),
(null, null),
(1, null),
(1, null),
(null, 2),
(null, 2)

--This Insert fails
insert into tblEmployee values
(3, 4),
(3, 4)
Run Code Online (Sandbox Code Playgroud)