Oracle Unique Constraint based on column value

旧时模样 提交于 2019-11-29 21:02:56

问题


I have the following unique constraint

dup_Checklist_QNum UNIQUE (QUESTION_NO, IS_ACTIVE)

I am trying to prevent two questions having the same question number while being active (IS_ACTIVE value = 1).

All seemed fine until I had to rev a question for the second time.

QUESTION_NO=1, TEXT="Have you..", REV=1, IS_ACTIVE=0  
QUESTION_NO=1, TEXT="Have you..", REV=2, IS_ACTIVE=0  <-- This should be ok but constraint was violated
QUESTION_NO=1, TEXT="Have you..", REV=3, IS_ACTIVE=1
QUESTION_NO=1, TEXT="Have you..", REV=3, IS_ACTIVE=1 <-- This should be throw constraint exception 

I need the constraint to only apply when IS_ACTIVE=1


回答1:


You can create a unique function-based index

CREATE UNIQUE INDEX idx_dup_active
    ON <<table name>>( CASE WHEN is_active = 1
                            THEN question_no
                            ELSE NULL
                        END );

This takes advantage of the fact that Oracle b-tree indexes do not store data where the leaf block data would be entirely NULL.



来源:https://stackoverflow.com/questions/11335899/oracle-unique-constraint-based-on-column-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!