gpt4 book ai didi

sql - 从 Oracle DB 中查找幽灵约束

转载 作者:行者123 更新时间:2023-12-03 14:38:28 26 4
gpt4 key购买 nike

我在表中有一个约束


CREATE TABLE "USERSAPPLICATIONS" (
"USERID" NUMBER NOT NULL ,
"APPLICATIONNAME" VARCHAR2 (30) NOT NULL ,
CONSTRAINT "PK_USERSAPPLICATIONS" PRIMARY KEY ("USERID","APPLICATIONNAME")
)
/

两周前,我修改了表,添加了一些列,删除了约束“PK_USERSAPPLICATIONS”并添加了代理键。我可以在 Oracle SQL Developer 中看到约束 PK_USERSAPPLICATIONS 不再存在。

无论如何,当我尝试添加两个具有相同用户 ID/应用程序名称组合的条目时,我收到一个错误

SQL Error: ORA-00001: unique constraint (ACCOUNTMP1.PK_USERSAPPLICATIONS) violated
00001. 00000 - "unique constraint (%s.%s) violated"
*Cause: An UPDATE or INSERT statement attempted to insert a duplicate key.
For Trusted Oracle configured in DBMS MAC mode, you may see
this message if a duplicate entry exists at a different level.
*Action: Either remove the unique restriction or do not insert the key.

当我执行语句

SELECT *
FROM user_cons_columns
WHERE constraint_name = 'PK_USERSAPPLICATIONS'

我得到零行。怎么可能? Oracle 不应该对约束 PK_USERSAPPLICATIONS 有任何了解,因为它已经在几周前被删除,而且我在数据库中也看不到它。

最佳答案

你还有那个约束使用的索引吗?因为除非你包含 DROP INDEX当您删除约束时,它仍然存在。从...开始

SELECT * 
FROM user_indexes
WHERE index_name = 'PK_USERSAPPLICATIONS'
/

或者,
select index_name 
from user_indexes
where table_name = 'USERSAPPLICATIONS'
and uniqueness='UNIQUE'
/

或者
select index_name 
from user_ind_columns
where table_name = 'USERSAPPLICATIONS'
and column_name in ('USERID' ,'APPLICATIONNAME')
/

编辑

概念证明
SQL> create table t23 (id number not null, alt_key varchar2(10) not null)
2 /

Table created.

SQL> create unique index t23_idx on t23 (id)
2 /

Index created.

SQL> alter table t23 add constraint t23_pk primary key (id) using index
2 /

Table altered.

SQL> insert into t23 values (1, 'SAM I AM')
2 /

1 row created.

SQL> insert into t23 values (1, 'MR KNOX')
2 /
insert into t23 values (1, 'MR KNOX')
*
ERROR at line 1:
ORA-00001: unique constraint (APC.T23_PK) violated

SQL>

所以约束有效。如果我们在没有 DROP INDEX 子句的情况下删除它会发生什么?
SQL> alter table t23 drop constraint t23_pk
2 /

Table altered.

SQL> insert into t23 values (1, 'MR KNOX')
2 /
insert into t23 values (1, 'MR KNOX')
*
ERROR at line 1:
ORA-00001: unique constraint (APC.T23_IDX) violated


SQL>

请注意错误消息中的细微变化。第二个失败引用了索引名称,而原始消息引用了约束。如果索引名称与约束名称相同,则很难诊断。

如果您没有显式地预先创建唯一索引,Oracle 的默认行为是创建非唯一索引。因此,在不删除索引的情况下删除约束不会导致此问题。 (警告这种行为对于 11g 来说是正确的。我推测 - 但不能确定 - 在早期版本中也是如此)。

关于sql - 从 Oracle DB 中查找幽灵约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2372163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com