首先创建测试表
--创建父表
create table dept
(
deptno number(2),
dname varchar2(14),
loc varchar2(13)
);
--创建子表
create table emp
(
empno number(4) constraint EMP_PK primary key,
ename varchar2(10),
job varchar2(9),
mgr number(4),
hiredate date,
sal number(7,2),
comm number(7,2),
deptno number(2) constraint EMP_PK_DEPTNO references DEPT(deptno)
);
deptno number(2) constraint EMP_PK_DEPTNO references DEPT(deptno)
*
ERROR at line 10:
ORA-02270: no matching unique or primary key for this column-list
可以看到 当父表的外部键 不是主键的时候 子表定义外部键会出现02270 错误, 必须把主表的外部键定义为主键或者唯一约束
下面定义外部键为唯一约束
alter table dept
add constraint DEPT_UN unique(deptno);
在插入 删除 更新表的时候 参考完整性约束(referential Integrity ,RI)都将发挥作用
为了防止出现父表删除出现错误,我们可以在子表创建外键约束的时候添加 on delete cascade 选项
首先尝试修改原来的外键约束
SQL> alter table emp modify deptno constraint EMP_PK_DEPTNO references DEPT(deptno) on delete cascade;
alter table emp modify deptno constraint EMP_PK_DEPTNO references DEPT(deptno) on delete cascade
*
ERROR at line 1:
ORA-02275: such a referential constraint already exists in the table
发现修改约束行不通 只能先进行删除 再添加
alter table emp drop constraint EMP_PK_DEPTNO ;
执行成功 再进行添加
alter table emp add constraint EMP_PK_DEPTNO FOREIGN KEY(deptno) references DEPT(deptno) on delete cascade;
注意这里要添加一个foreign key
这时就可以进行级联删除了
同时还有另外两个参数
delete set null : 将所有相关记录的外部码字段值设置为NULL
delete no action: 不做任何操作
可设置删除后的不同操作