天天看点

ORA-02292: 违反完整约束条件 (***.FK_****) - 已找到子记录

执行

DELETE FROM dept WHERE deptno = dept_no;

时报错

第 1 行出现错误:
ORA-02292: 违反完整约束条件 (SCOTT.FK_DEPTNO) - 已找到子记录
ORA-06512: 在 "SCOTT.PTESTFOUND", line 5
ORA-06512: 在 line 3
           

查询约束具体状况

OWNER CONSTRAINT_NAME CONSTRAINT_TYPE TABLE_NAME SEARCH_CONDITION R_OWNER R_CONSTRAINT_NAME DELETE_RULE STATUS DEFERRABLE DEFERRED VALIDATED GENERATED
SCOTT PK_DEPT P DEPT ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED USER NAME
SCOTT PK_EMP P EMP ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED USER NAME
SCOTT FK_DEPTNO R EMP SCOTT PK_DEPT NO ACTION ENABLED NOT DEFERRABLE IMMEDIATE VALIDATED USER NAME

CONSTRAINT_TYPE:

P --primary key unique and not null,可以是多个column的联合

R --forgien key parent table 中的primary key中的values必须包含child table中所有的values. share column的parent-child 关系

或者直接通过约束名称查找,更加直观显示:

select a.constraint_name, a.table_name, b.constraint_name ,b.table_name
 from user_constraints a, user_constraints b
 where a.constraint_type = 'R' and b.constraint_type = 'P' 
 and a.r_constraint_name = b.constraint_name
 and a.constraint_name = 'FK_DEPTNO'
           
CONSTRAINT_NAME TABLE_NAME CONSTRAINT_NAME TABLE_NAME
FK_DEPTNO EMP PK_DEPT DEPT

EMP表中有外键FK_DEPTNO中关联的字段

DEPTNO

与表DEPT的主键PK_DEPT中关联字段

DEPTNO

所以删除EMP表某一行时需要先把表DEPT中对应的一行先删除;或者删除/禁用EMP表中外键FK_DEPTNO约束。

参考《oracle 添加、修改、删除、约束-语法》

--删除所有外键约束 的Sql代码  
select 'alter table '||table_name||' drop constraint '||constraint_name||';' from user_constraints where constraint_type='R';
alter table EMP drop constraint FK_DEPTNO;
--禁用所有外键约束的Sql代码 
select 'alter table '||table_name||' disable constraint '||constraint_name||';' from user_constraints where constraint_type='R'`
alter table EMP disable constraint FK_DEPTNO;
--启用所有外键约束的Sql代码 
select 'alter table '||table_name||' enable constraint '||constraint_name||';' from user_constraints where constraint_type='R'   
alter table EMP enable constraint FK_DEPTNO;
           

我直接执行禁用EMP表的外键关联

删除语句执行成功。