SQL约束条件检查:如果column0为null,column1不为null,反之亦然

SQL Constraint conditional Check: if column0 is null, column1 is not null and vice versa

我有关于 SQL 约束的问题,以实现以下行为:

TableA 有两列 column0 和 column1,其中只有一个在数据输入时可以为 NULL: 例如。: 如果 column0 为 null,则 column1 不能为 null 如果 column1 为 null,column0 不能为 null

为了实现这一点,我构建了以下 SQL 约束条件:

CONSTRAINT column01_not_null_chk
CHECK (
  ( column0 IS NOT NULL
  AND column1 IS NULL )
OR
  ( column1 IS NOT NULL
  AND column0 IS NULL ) )

实现我的行为是否正确?因为所有SQL都因为这个约束被拒绝了

似乎在 SQL 服务器上运行良好:

create table t (
     column0 int null
   , column1 int null
, CONSTRAINT column01_not_null_chk
CHECK (
  ( column0 IS NOT NULL
  AND column1 IS NULL )
OR
  ( column1 IS NOT NULL
  AND column0 IS NULL ) )
);

insert into t values (null,1),(1,null);

select * from t;
--insert into t values (null,null) /* fail */
--insert into t values (1,1) /* fail */

rextester 演示http://rextester.com/OQZNE39497

returns:

+---------+---------+
| column0 | column1 |
+---------+---------+
| NULL    | 1       |
| 1       | NULL    |
+---------+---------+

您描述的条件意味着其中至少有一个必须是有价值的。所以你的约束应该更正为:

CONSTRAINT column01_not_null_chk
CHECK (column0 IS NOT NULL OR column1 IS NOT NULL)