1. 程式人生 > >判斷子表外鍵約束參數類型

判斷子表外鍵約束參數類型

表數 數據處理 line 否則 RR 了解 nal p s 添加

判斷子表外鍵約束參數類型

前言:在存在主外鍵約束的父子表關系中,刪除父表的數據,子表的數據需要首先刪除,否則報錯

#在外鍵約束的參數中有三種模式:默認無配置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,可以有助於數據處理的思考

判斷子表外鍵約束參數類型