删除唯一约束不起作用

Dropping an unique constraint does not work

我试图在我的数据库中删除一个唯一约束:

ALTER TABLE MyDbAdmin.myTable
DROP UNIQUE (myCol);

控制台显示删除有效,但是当我尝试插入重复的记录时 myCol,返回 ORA-00001: unique constraint 错误。

我试了看table的约束页面,唯一约束确实没有了。此外,如果我 运行 相同的 SQL 再次删除约束,它会返回 ORA-02442: Cannot drop nonexistent unique key.

以上查询是 运行 使用帐户 myDbUser,这是导致上述奇怪行为的原因吗?

如果您粘贴了整个错误行,可能会有用。为什么?我们会看到唯一的约束名称,这可能是您问题的关键。

这是我的想法:有一个包含 myCol 列的复合唯一索引。

SQL> create table test (mycol number, id number);

Table created.

SQL> alter table test add constraint ukt unique (mycol);

Table altered.

SQL> create unique index i1t on test (mycol, id);

Index created.

SQL>

测试:

SQL> -- this is OK
SQL> insert into test values (1, 1);

1 row created.

SQL> -- but, this will fail
SQL> insert into test values (1, 1);
insert into test values (1, 1)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.UKT) violated


SQL>

违反了 UKT 约束,所以 - 让我们放弃它并重试:

SQL> alter table test drop unique (mycol);

Table altered.

SQL> insert into test values (1, 1);
insert into test values (1, 1)
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.I1T) violated


SQL>

看看现在违反了哪个约束? I1T.

找出违反了哪个约束后,请尝试使用以下其中一项查找更多信息:

SQL> select column_name from user_cons_columns where constraint_name = 'I1T';

no rows selected

SQL> select column_name from user_ind_columns where index_name = 'I1T';

COLUMN_NAME
-----------------------------------------------------------------------------
MYCOL
ID

SQL>

也许您的唯一索引是在创建约束之前创建的:

create table t(col1 number);
create unique index t_idx on t(col1);
alter table t add constraint t_unique unique(col1);
insert into t values(1);
--> 1 row created
insert into t values(1);
--> ORA-00001: unique constraint (TEST.T_UNIQUE) violated
alter table t drop unique (col1);
insert into t values(1);
--> ORA-00001: unique constraint (TEST.T_IDX) violated

虽然唯一索引 T_IDX 没有出现在 user_constraints 中,但它显示在错误消息中。

如果索引是作为 "alter table ... add constraint" 的一部分在内部创建的,那么您可以在删除约束后插入重复项,因为支持约束的索引与约束一起被删除。因此,如果没有 "create unique index",代码将按预期工作:

create table t(col1 number);
-- create unique index t_idx on t(col1);
alter table t add constraint t_unique unique(col1);
insert into t values(1);
--> 1 row created
insert into t values(1);
--> ORA-00001: unique constraint (TEST.T_UNIQUE) violated
alter table t drop unique (col1);
insert into t values(1);
--> 1 row created