简体   繁体   中英

UNIQUE inside CHECK constraint

This question is new twist of An IF inside a check constraint SQL . I want to do something similar to the following check (which throws an ORA-00936: missing expression exception):

ALTER TABLE t_table
    ADD CONSTRAINT chk_unique_active CHECK
    ( 
        ( tb_active = 0 ) OR  
        ( tb_active = -1 AND UNIQUE(tb_active, tb_img, tb_objid)) 
    );

The objetive is to be sure (at DBMS level) that only one row with the same objid is active although inactive rows can be duplicated (an historical view of the rows).

It can be done in a trigger but it seems to be better using the check as explained in UNIQUE constraint vs checking before INSERT question.

is this possible?

Do this with a unique index:

create unique index unq_table_active 
    on ( (case when tb_active = -1 then tb_img end),
         (case when tb_active = -1 then tb_objid end)
       ) 

Oracle allows multiple rows with NULL values in a unique index.

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