0

昨夜、以下のチェック制約の何が問題なのかを突き止めようと何時間も費やしました。次のルールを適用したい:

  • すべての行が null である
  • または、Col1 が null ではなく、他の列の 1 つだけが null ではありません (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 に答える