在TABLE CREATE中使用WHERE子句进行UNIQUE NONCLUSTERED?

时间:2014-06-20 17:51:40

标签: sql-server-2008-r2 where-clause unique-constraint create-table

我知道可以为现有表中的字段创建带有UNIQUE子句的WHERE约束,但是可以在CREATE TABLE语句中创建它们吗?即类似的东西(我知道这是无效的语法):

CREATE TABLE [ExampleTable]
(
    [ID]    INT IDENTITY(1,1) PRIMARY KEY   NOT NULL,
    [Name]  NVARCHAR(20)    DEFAULT ''  NOT NULL UNIQUE NONCLUSTERED WHERE [Name] <> ''
)

这里的目标是[Name]字段必须是唯一的,除非它是一个空字符串。

1 个答案:

答案 0 :(得分:0)

不,你不能。

您可以创建过滤后的索引,但不能创建过滤后的约束,语法不允许这样做。

[ CONSTRAINT constraint_name ] 
{ 
    [ NULL | NOT NULL ] 
    { PRIMARY KEY | UNIQUE } 
        [ CLUSTERED | NONCLUSTERED ] 
        [ WITH FILLFACTOR =fillfactor ] 
        [ WITH ( index_option [, ...n ] ) ]
        [ ON { partition_scheme_name (partition_column_name) 
            | filegroup | "default" } ] 
    | [ FOREIGN KEY ] 
        REFERENCES [ schema_name . ] referenced_table_name 
            [ ( ref_column ) ] 
        [ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] 
        [ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] 
        [ NOT FOR REPLICATION ] 
    | CHECK [ NOT FOR REPLICATION ] ( logical_expression )
}