2015-02-23 56 views
2

給定一個包含兩列col1和col2的表,如何使用Oracle CHECK約束來確保col2中允許的內容取決於相應的col1值。根據另一列的值在一列上添加多個CHECK約束

具體地說,

  • 如果COL1有A,然後相應COL2值必須小於50;
  • 如果col1有B,那麼相應的col2值必須小於100;
  • 如果COL1有C,則對應COL2值必須小於150

感謝您的幫助!

回答

1

您需要使用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. 
2

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

CREATE TABLE MYDEPT(DEPT INT PRIMARY KEY CHECK(DEPT IN(10,20,30 check constraint, 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)))

要在單個列中添加多個檢查約束,您必須定義多個用戶定義的檢查約束,如上所示。