我已经创建了具有5列的唯一约束,如下所示:ALTER TABLE CAMPAIGN_MSISDN添加CONSTRAINT ADWISER_UNIQUE UNIQUE(campaign_id,msisdn,running_date,time_frame,status);status具有5枚举形式的值。但是我希望ADWISER_UNIQUE仅检查2/5状态下的约束,而不是所有状态。我该怎么做。谢谢大家!
您可以在条件下使用unique index
。请参阅以下示例:
SQL> create table test123 (col1 number, col2 number, col3 number);
Table created.
SQL> -- You need something like this (solution)
SQL> create unique index test123_ix01 on test123(case when col3 in (1,2) then col1 end,
2 case when col3 in (1,2) then col2 end,
3 case when col3 in (1,2) then col3 end);
Index created.
SQL>
现在,让我们检查它是否有效:
SQL> insert into test123 values (1,2,3);
1 row created.
SQL> insert into test123 values (1,2,3);
1 row created.
SQL> insert into test123 values (1,2,1);
1 row created.
SQL> insert into test123 values (1,2,2); -- this is of your interest -- see col3 value
1 row created.
SQL> insert into test123 values (1,2,2); -- this is of your interest -- see col3 value
insert into test123 values (1,2,2)
*
ERROR at line 1:
ORA-00001: unique constraint (TEJASH.TEST123_IX01) violated
SQL>
SQL> select * from test123;
COL1 COL2 COL3
---------- ---------- ----------
1 2 3
1 2 3
1 2 1
1 2 2
SQL>
哇!当col3
为2时,它限制了col3
的多个值,并且在col3
为1的情况下,其行为相同。允许所有其他状态多次插入。
干杯!