根据另一列的值在一列上添加多个 CHECK 约束

Add multiple CHECK constraints on one column depending on the values of another column

给定一个包含两列 col1 和 col2 的 table,我如何使用 Oracle CHECK 约束来确保 col2 中允许的内容取决于相应的 col1 值。

具体来说,

感谢您的帮助!

您需要使用 case 语句,例如。类似于:

create table test1 (col1 varchar2(2),
                    col2 number);

alter table test1 add constraint test1_chk check (col2 < case when col1 = 'A' then 50
                                                              when col1 = 'B' then 100
                                                              when col1 = 'C' then 150
                                                              else col2 + 1
                                                         end);

insert into test1 values ('A', 49);
insert into test1 values ('A', 50);
insert into test1 values ('B', 99);
insert into test1 values ('B', 100);
insert into test1 values ('C', 149);
insert into test1 values ('C', 150);
insert into test1 values ('D', 5000);

commit;

输出:

1 row created.

insert into test1 values ('A', 50)
Error at line 2
ORA-02290: check constraint (MY_USER.TEST1_CHK) violated

1 row created.

insert into test1 values ('B', 100)
Error at line 4
ORA-02290: check constraint (MY_USER.TEST1_CHK) violated

1 row created.

insert into test1 values ('C', 150)
Error at line 6
ORA-02290: check constraint (MY_USER.TEST1_CHK) violated

1 row created.

Commit complete.

添加 check constraint 使用 case 语句

CREATE TABLE tbl
(
  col1 varchar(10),
  col2 numeric(4),
  CONSTRAINT check_cols_ctsr
  CHECK (CASE WHEN col1='A' THEN col2 ELSE 1 END <50 AND 
         CASE WHEN col1='B' THEN col2 ELSE 1 END <100 AND 
         CASE WHEN col1='C' THEN col2 ELSE 1 END <150)
);

CREATE TABLE MYDEPT (DEPT INT PRIMARY KEY CHECK(DEPT IN(10,20,30,40)),DEPTNAME VARCHAR(50) DEFAULT 'NOT GIVEN' CHECK(DEPTNAME=UPPER(DEPTNAME)) UNIQUE NOT NULL, DEPTLOC VARCHAR(50) DEFAULT 'NOT GIVEN' CONSTRAINT CHECK_DEPT CHECK (DEPTLOC IN ('BBSR','HYD','MUMBAI','PUNE')), CONSTRAINT CHECK_DEPT1 CHECK (DEPTLOC=UPPER( DEPTLOC)))

要在单个列中添加多个检查约束,您必须定义多个用户定义的检查约束,如上所示。