简体   繁体   English

Oracle SQL - 可以在检查约束中使用CASE来确定数据属性吗?

[英]Oracle SQL - can CASE be used in a check constraint to determine data attributes?

I'm using Oracle 10g and I want to apply a constraint to a table where the value entered for one column determines whether another column IS NULL or IS NOT NULL. 我正在使用Oracle 10g,我想将约束应用于一个表,其中为一列输入的值确定另一列是IS NULL还是IS NOT NULL。 Column1 can only contain 1 or 0; Column1只能包含1或0; Column2 is VARCHAR2(255). Column2是VARCHAR2(255)。

I know that the following works: 我知道以下工作:

CONSTRAINT ck_1 CHECK ((col1=1 AND col2 IS NOT NULL) OR (col1=0 AND col2 IS NULL));

However, I was wondering if it is possible to use CASE to perform this constraint and set the attribute NOT NULL on col2, or can CASE only be used to define values? 但是,我想知道是否可以使用CASE来执行此约束并在col2上设置属性NOT NULL,或者CASE是否只能用于定义值? ie could something like this work: 即可能像这样的工作:

CONSTRAINT ck_1 CHECK (CASE WHEN col1=1 THEN col2 IS NOT NULL ELSE col2 IS NULL END);

由于CASE表达式必须返回一个值,并且检查约束是布尔值,因此您必须将结果与某些内容进行比较,例如:

CONSTRAINT ck_1 CHECK (CASE WHEN col2 IS NOT NULL THEN 1 ELSE 0 END = col1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM