【案例】ORA-02298
参考:http://blog.163.com/yvtong@126/blog/static/8753524720132223343722/
ORA-39083: Object type REF_CONSTRAINT:"TEST"."FK_AN_ID" failed to create with error:
ORA-02298: cannot validate (TEST.FK_AN_ID) - parent keys not found
Failing sql is:
ALTER TABLE "TEST"."ROWER_INFO" ADD CONSTRAINT "FK_AN_ID" FOREIGN KEY ("LOAN_ID") REFERENCES "TEST"."AN_REQUEST" ("ID") ENABLE
原因:
表ROWER_INFO里,有外键连接到另一个表AN_REQUEST的主键, 在表ROWER_INFO的外键列插入的值 在表AN_REQUEST的主键列找不到就不能插入。这往往由于表在不同的时间点导出,主表中有新的业务数据。
而此次利用数据泵导出TEST用户下的所有对象,导入到另一用户下,报错。原因是子表ROWER_INFO多了一行数据,造成创建外键约束失败
SQL> select * from "TEST"."ROWER_INFO" a where not exists ( select 1 from "TEST"."AN_REQUEST" b where b.ID=a.LOAN_ID);
125509 128043 D 0 Scott F 27-10月-78
SQL> delete from "TEST"."ROWER_INFO" a where not exists ( select 1 from "TEST"."AN_REQUEST" b where b.ID=a.LOAN_ID);
1 row deleted.
SQL> ALTER TABLE "TEST"."ROWER_INFO" ADD CONSTRAINT "FK_AN_ID" FOREIGN KEY ("LOAN_ID") REFERENCES "TEST"."AN_REQUEST" ("ID") ENABLE;
Table altered.
获取删除多余数据的SQL:
SELECT ' delete from '
||a.table_name
||' a where not exists ( select 1 from '
||c_pk.table_name
|| ' b where b.'
|| b.column_name
||'=a.'
||a.column_name
||');'
FROM user_cons_columns a
JOIN user_constraints c
ON a.constraint_name = c.constraint_name
JOIN user_constraints c_pk
ON c.r_constraint_name = c_pk.constraint_name
JOIN user_cons_columns b
ON c_pk.constraint_name = b.constraint_name
WHERE c.constraint_type = 'R'
AND a.table_name = '&Table_Name'
AND a.constraint_name ='&FK_NAME';