sam*_*amg 3 sql oracle constraints
我必须更改表以在特定列上创建条件非空约束,以便在 col1 和 col2 具有值时它不能为空。
首先,什么是条件非空约束?
其次,您能否提供有关如何完成此类操作的语法?
您需要检查的谓词是
if (col1 is not null and col2 is not null) then specific is not null
Run Code Online (Sandbox Code Playgroud)
谓词if A then B 可以写成not A or B
请注意,优先级(not A) or B参见此处的讨论
所以你得到:
alter table spec add constraint my_spec
check (not (col1 is not null and col2 is not null) or specific is not null);
Run Code Online (Sandbox Code Playgroud)
如果 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);
Run Code Online (Sandbox Code Playgroud)
如果 col1 和 col2 都在 NOT NULL 中具体定义
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
Run Code Online (Sandbox Code Playgroud)
在现有表上,check只有在现有数据完成验证时才可以添加此项,否则会出现此异常
ORA-02293: cannot validate (OWNER.MY_SPEC) - check constraint violated
Run Code Online (Sandbox Code Playgroud)
要查找违反新规则的行,只需查询
select * from spec
where NOT (not (col1 is not null and col2 is not null) or specific is not null);
Run Code Online (Sandbox Code Playgroud)
您必须删除这些行或设置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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1857 次 |
| 最近记录: |