昨晚我花了几个小时试图弄清楚下面的检查约束有什么问题。我想强制执行以下规则:
我能够插入仅设置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)
)
)
)
答案 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))
)
)
)