简体   繁体   中英

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. Column1 can only contain 1 or 0; Column2 is 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? 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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