sql - Oracle:两个条件都为真时的条件非空约束

标签 sql oracle constraints

我必须更改表以在特定列上创建条件非空约束,以便在 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/

相关文章:

mysql - 更改 mysql 中的表时获取受影响的行

mysql - 在 select where 语句中展开查询结果

mysql - 如果不存在类似记录则添加新记录

oracle - 不要传输 blob

.net - oracle sql Developer中的J2SE SDK配置

swift - UITableviewCell : set constraints programmatically inside ContentView using autoresize

mysql - 我应该如何根据以下要求创建一个表? [SQL]

python - SQL:使用现有表/df 中的信息创建新表/df

database - 学习 Cocoa 数据库开发的推荐资源?

neo4j - Neo4J 约束中的非空属性