17,377
社区成员
发帖
与我相关
我的任务
分享
-- 这个要加 unique index 来实现,加 unique 约束不可以的
SQL>
SQL> -- 当Status=1时,ABC不能重复。 即当Status<>1时,ABC可以重复。
SQL> create table test(ABC int, Status int);
Table created
SQL> create unique index uix_test on test(decode(status,1,ABC,null));
Index created
SQL> insert into test(ABC, status) values(1,1);
1 row inserted
SQL> insert into test(ABC, status) values(1,1); -- 失败
insert into test(ABC, status) values(1,1)
ORA-00001: 违反唯一约束条件 (ORACLE.UIX_TEST)
SQL> insert into test(ABC, status) values(1,0);
1 row inserted
SQL> insert into test(ABC, status) values(1,0);
1 row inserted
SQL> insert into test(ABC, status) values(1,NULL);
1 row inserted
SQL> insert into test(ABC, status) values(2,1);
1 row inserted
SQL> insert into test(ABC, status) values(2,2);
1 row inserted
SQL> insert into test(ABC, status) values(3,2);
1 row inserted
SQL> insert into test(ABC, status) values(3,2);
1 row inserted
SQL> select * from test;
ABC STATUS
--------------------------------------- ---------------------------------------
1 1
1 0
1 0
1
2 1
2 2
3 2
3 2
8 rows selected
SQL> drop table test purge;
Table dropped
SQL>