Oracle:禁用FK,现在无法重新启用FK

时间:2014-08-28 09:38:41

标签: sql database oracle foreign-keys

我需要删除其中一个db视图中的条目,当我尝试这样做时,我收到了参照完整性错误消息。我不想删除表中的条目,所以我决定禁用FK并删除db视图中的条目,然后重新启用FK。

工作正常,直到我尝试重新启用我的FK并收到以下错误消息。

Error report:
SQL Error: ORA-02298: cannot validate (DB.ABCD) - parent keys not found
02298. 00000 - "cannot validate (%s.%s) - parent keys not found"
*Cause:    an alter table validating constraint failed because the table has
           child records.

我知道这应该是显而易见的,但我在这里有点失落。任何帮助都是预先确定的。

1 个答案:

答案 0 :(得分:2)

您的值与外键不匹配,例如:

create table t1 as
select 1 id from dual

create table t2 as
select 1 id, 1 fk from dual

alter table t1 add primary key(id);
alter table t2 add primary key(id);


alter table t2 add constraint t2_fk foreign key(fk) references t1(id)

alter table t2 disable constraint t2_fk

insert into t2 values (2, 2)

alter table t2 enable constraint t2_fk

ORA-02298: cannot validate (ODCS_DVLP.T2_FK) - parent keys not found

此外,您可能已从父表中删除了行:

delete t1
1 row(s) deleted.

alter table t2 enable constraint t2_fk
ORA-02298: cannot validate (ODCS_DVLP.T2_FK) - parent keys not found

正如您所看到的,我无法重新启用外键,因为fk表的t2列具有t1表中不存在的值1}}要重新启用的表,您必须将此值设置为null:

update t2
   set fk = null
 where not exists (select null from t1 where t1.id = t2.fk)

1 row(s) updated.

alter table t2 enable constraint t2_fk

Table altered

或删除包含父表中不具有的值的行:

delete t2
 where not exists (select null from t1 where t1.id = t2.fk)

alter table t2 enable constraint t2_fk

Table altered