0

昨晚我花了几个小时试图找出下面的检查约束有什么问题。我想执行以下规则:

  • 要么所有行都为空
  • 或者 Col1 不为空且其他列中只有一列不为空(如果设置了 col4,则应设置为 true)

我能够插入仅设置 Col1 的行,但我希望抛出一个错误。

    create table TestTable
    (
        Col1 varchar(10) null,
        Col2 varchar(10) null,
        Col3 varchar(10) null,
        Col4 bit null,
    )


    alter table TestTable add constraint X check
    (
        (Col1 is null and Col2 is null and Col3 is null and Col4 is null) or
        (
            Col1 is not null and
            (
                (Col2 is not null and Col3 is null and Col4 is null) or
                (Col2 is null and Col3 is not null and Col4 is null) or
                (Col2 is null and Col3 is null and Col4 = 1)
            )
        )
    )
4

1 回答 1

0

相等比较不适用于 NULL:

alter table TestTable add constraint X check
(
    (Col1 is null and Col2 is null and Col3 is null and Col4 is null) or
    (
        Col1 is not null and
        (
            (Col2 is not null and Col3 is null and Col4 is null) or
            (Col2 is null and Col3 is not null and Col4 is null) or
            (Col2 is null and Col3 is null and (Col4 is not null and Col4 = 1))
        )
    )
)
于 2014-04-28T16:36:52.753 回答