執行
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表的外鍵關聯
删除語句執行成功。