我在此SQL检查约束中有什么逻辑错误?

时间:2014-04-28 16:13:08

标签: sql-server check-constraint

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

  • 所有行都为空
  • 或者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)
            )
        )
    )

1 个答案:

答案 0 :(得分: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))
        )
    )
)