标签:size ref create str 否则 key err user weight
判断子表外键约束参数类型
前言:在存在主外键约束的父子表关系中,删除父表的数据,子表的数据需要首先删除,否则报错
#在外键约束的参数中有三种模式:默认无配置NO ACTION ,级联删除 ON DELETE CASCADE,父表删除的相关数据,子表外键约束列对应的数据置为null
#如何查询外键约束类型是什么参数
#直接删除父表的记录测试:
delete scott.dept where deptno=20
*
ERROR at line 1:
ORA-02292: integrity constraint (SCOTT.FK_DEPTNO) violated - child record found
#子表还存在数据,且外键约束类型为默认,因此删除父表数据,需要手工提取删除子表的相关记录
#查询子表的外键约束类型
SCOTT > select OWNER,CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME,R_OWNER,R_CONSTRAINT_NAME,DELETE_RULE from USER_CONSTRAINTS where CONSTRAINT_TYPE=‘R‘
OWNER CONSTRAINT CONSTRAINT TABLE_NAME R_OWNER R_CONSTRAI DELETE_RUL
---------- ---------- ---------- ---------- ---------- ---------- ----------
SCOTT FK_DEPTNO R EMP SCOTT PK_DEPT NO ACTION
#添加一个外键约束:为 on delete cascade参数
SCOTT > alter table emp add constraint fk_deptno foreign key(deptno) references dept(deptno) on delete cascade;
#查询
SCOTT > select OWNER,CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME,R_OWNER,R_CONSTRAINT_NAME,DELETE_RULE from USER_CONSTRAINTS where CONSTRAINT_TYPE=‘R‘;
OWNER CONSTRAINT CONSTRAINT TABLE_NAME R_OWNER R_CONSTRAI DELETE_RUL
---------- ---------- ---------- ---------- ---------- ---------- ----------
SCOTT FK_DEPTNO R EMP SCOTT PK_DEPT CASCADE
#对比:从视图: user_constraints视图中的 delete_rule列可以看出外键约束的参数类型
#测试 on delete set null参数现象:
SYS > create table hr.emp as select * from scott.emp;
SYS > grant references on scott.dept to hr;
SYS > alter table hr.emp add constraint fk_deptno foreign key (deptno) references scott.dept(deptno) novalidate;
SYS > alter table hr.emp drop constraint fk_deptno;
SYS > alter table hr.emp add constraint fk_deptno foreign key (deptno) references scott.dept(deptno) on delete set null;
SYS > delete scott.dept where deptno=20;
1 row deleted.
SYS > select * from hr.emp where deptno=20;
no rows selected
SYS > select * from hr.emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- ------------------- ---------- ---------- ----------
7900 JAMES CLERK 7698 1981-12-03 00:00:00 950 30
7902 FORD ANALYST 7566 1981-12-03 00:00:00 5000
#外键约束参数,会导致对父表delete操作需要考虑子表的数据,了解外键约束三种参数,默认不处理,delete级联删除子表数据,set null对子表复合的外键列置为Null,可以有助于数据处理的思考
标签:size ref create str 否则 key err user weight
原文地址:https://www.cnblogs.com/lvcha001/p/9196065.html