SQL Server:指定唯一的可选列

Man*_*ngo 4 null sql-server unique-constraint

SQL Server 有一个带有可选唯一列的怪癖:null一个表中不能有多个。

例如:

create table employees (
    id int identity(1,1) primary key,
    givenname nvarchar(24) not null,
    familyname varchar(24) not null,
    tfn char(9) unique  --  optional, but unique
);
Run Code Online (Sandbox Code Playgroud)

(在澳大利亚,我们有一个纳税人独有的税号)。

以下是一种解决方法:

create table employees (
    id int identity(1,1) primary key,
    givenname nvarchar(24) not null,
    familyname varchar(24) not null,
    tfn char(9)
);
CREATE UNIQUE NONCLUSTERED INDEX uq_employees_tfn ON employees(tfn)
WHERE tfn IS NOT NULL;
Run Code Online (Sandbox Code Playgroud)

是否可以命名一个唯一的约束并给它上述条件是一种类似于第一个示例的方式?也就是说,是否可以在列定义中包含更复杂的约束?

Pau*_*ite 8

是否可以命名一个唯一的约束并给它上述条件是一种类似于第一个示例的方式?也就是说,是否可以在列定义中包含更复杂的约束?

是的,以下有效(仅在 SQL Server 2016 及更高版本中):

create table employees (
    id int identity(1,1) primary key,
    givenname nvarchar(24) not null,
    familyname varchar(24) not null,
    tfn char(9) NULL 
        INDEX uq_employees_tfn 
        UNIQUE (tfn) 
        WHERE tfn IS NOT NULL
);
Run Code Online (Sandbox Code Playgroud)

内联语法产生与单独的CREATE UNIQUE INDEX. 后续的 DDL 将需要像索引而不是约束一样管理它。

它在CREATE TABLE文档中不是很清楚,但在示例 S 中进行了说明。