我必须更改表以在特定列上创建条件非空约束,以便在 col1 和 col2 具有值时它不能为空。
首先,什么是条件非空约束?
其次,您能否提供一个有关如何完成此类事情的语法?
最佳答案
你需要检查的谓词是
if (col1 is not null and col2 is not null) then specific is not null
谓词if A then B
可以写成not A or B
注意优先级是(不是A)或B
见讨论here
所以你得到:
alter table spec add constraint my_spec
check (not (col1 is not null and col2 is not null) or specific is not null);
如果 col1 或 col2 为空,则特定为空
insert into spec(col1,col2,specific) values(null,null,null);
insert into spec(col1,col2,specific) values(1,null,null);
insert into spec(col1,col2,specific) values(null,1,null);
如果 col1 和 col2 都在 NOT NULL 中定义为 secific
insert into spec(col1,col2,specific) values(1,1,1);
insert into spec(col1,col2,specific) values(1,1,null);
-- ORA-02290: check constraint (REPORTER.MY_SPEC) violated
只有在现有数据完成验证时,您才能在现有表上添加此 check
,否则会出现此异常
ORA-02293: cannot validate (OWNER.MY_SPEC) - check constraint violated
要查找违反新规则的行,只需查询
select * from spec
where NOT (not (col1 is not null and col2 is not null) or specific is not null);
您必须删除这些行或将 specific
设置为非 NULL 值或将 col1 或 col2 设置为 NULL。
或者您可以使用 NOVALIDATE
选项启用约束,这可以容忍现有的违规行为,但强制新的更改遵循约束。
alter table spec add constraint my_spec
check (not (col1 is not null and col2 is not null) or specific is not null)
enable novalidate;
关于sql - Oracle:两个条件都为真时的条件非空约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53837290/