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

时间:2015-02-23 17:04:39

标签: sql oracle constraints

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

具体来说,

  • 如果col1有A,那么相应的col2值必须小于50;
  • 如果col1有B,那么相应的col2值必须小于100;
  • 并且如果col1具有C,则相应的col2值必须小于150。

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

使用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)
);

答案 1 :(得分:1)

您需要使用案例陈述,例如。类似的东西:

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.

答案 2 :(得分:0)

CREATE TABLE MYDEPT(DEPT INT PRIMARY KEY CHECK(DEPT IN(10,20,30,40)),DEPTNAME VARCHAR(50)DEFAULT&#39; NOT GIVEN&#39;  检查(DEPTNAME = UPPER(DEPTNAME))UNIQUE NOT NULL,DEPTLOC VARCHAR(50)DEFAULT&#39; NOT GIVEN&#39;  约束CHECK_DEPT检查(DEPTLOC IN(&#39; BBSR&#39;,&#39; HYD&#39;,&#39; MUMBAI&#39;&#39; PUNE&#39;)),CONSTRAINT CHECK_DEPT1 CHECK(DEPTLOC) = UPPER(DEPTLOC)))

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