某些列应全部填满或全部为空

时间:2019-07-04 11:14:17

标签: sql-server tsql check-constraints

我的表(10列)有4列(A,B,C,D),应该全部为空或全部填充。

我尝试通过以下方式进行操作:

constraint chk_same check (A is not null AND B is not null And C is not null AND is not null) OR (A is null AND B is null And C is null AND D is null)

它看起来很糟糕,有没有更好/更容易的方法?

1 个答案:

答案 0 :(得分:2)

您的方法很好。一种更通用的方法是计算NULL个值的数量并检查:

constraint chk_same
    check ( ((case when A is null then 1 else 0 end) +
             (case when B is null then 1 else 0 end) +
             (case when C is null then 1 else 0 end) +
             (case when D is null then 1 else 0 end)
            ) in (0, 4)
          ) ;

这是更通用的方法,因为您可以方便地检查4列中的2列还是4列中的3列具有NULL值。