简体   繁体   中英

Oracle: can I create a constraint that checks a value within a group

Thanks in advance for your help with this. In Oracle, is it possible to create a constraint so that there can only be one 'leader' per group:

How can I create a rule that prevents an additional 'leader' from being inserted if one already exists in a group?

在此处输入图像描述

Does this make sense? A function-based unique index:

SQL> create table test (col1 varchar2(10), col2 varchar2(10), col3 varchar2(10));

Table created.

SQL> create unique index ui1t on test (case when col2 = 'leader' then col1||col2 end);

Index created.

Testing:

SQL> insert into test values ('group1', 'leader', 'joe');

1 row created.

SQL> insert into test values ('group1', null    , 'diane');

1 row created.

SQL> insert into test values ('group1', null    , 'john');

1 row created.

SQL> insert into test values ('group1', null    , 'diane');

1 row created.

SQL> insert into test values ('group1', 'leader', 'mike');   --> another LEADER for GROUP1
insert into test values ('group1', 'leader', 'mike')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.UI1T) violated


SQL> insert into test values ('group1', 'leader', null);   --> another LEADER for GROUP1
insert into test values ('group1', 'leader', null)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.UI1T) violated


SQL>

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