我的实验过程
1.创建两个表
create table zb(n number not null primary key,b varchar2(10),c date default sysdate);
create table wb(n number not null primary key references zb(n),c date default sysdate);
2.给zb及wb分别insert into数据
insert into zb(n,b) values(3,'c');
insert into wb(n) values(1);
当给外表insert into上面三行(即与主表一样的n号时,系统没问题,错误产生)
当insert into 不相同的n号时
如:
insert into wb(n) values(4);
insert into wb(n) values(4)
Error at line 1
ORA-02291: integrity constraint (CSM.SYS_C00204894) violated - parent key not found
Script. Terminated on line 4.
说父表中没有数据发现。
说明什么,要么wb的行数少于zb的,要么最多和zb的行数一样多。
也就是说wb的n列,必须是zb的n列号码的子集。
3.测一下关于删除的例子:
delete from zb where n=1;
delete from zb where n=1
Error at line 1
ORA-02292: integrity constraint (CSM.SYS_C00204894) violated - child record found
Script. Terminated on line 5.
说明是互相约束的,如果删除zb即父表的行,那个n列中的值如果在wb中,那就出现上面的错误,
如果不在,即:
insert into zb(n,b) values(5,'c');
commit;
这个n=5不在wb中
即,再测试:
delete from zb where n=5;
1 row deleted.
说明是可以删除的
4.如何解决上述错误?
解决办法:
1.create table wb(n number not null primary key references zb(n) on delete cascade,c date default sysdate);
创建一个加on delete cascade参数的外键
给表插入上面的数据。
2.删除zb(即父表中的数据,n号在wb中)
delete from zb where n=2;
1 row deleted.
这说明这样是可以删除的。
叉插入的情况(主要测试wb)
插入依旧要遵守规则 ,在子表即wb中的行n号码,是zb中的n号的子集才成,如果不是,系统拒绝插入。
另:
如果外键的定义中没有on delete cascade参数
则删除zb的行,n的号在wb中的n号的话,则需要先删除wb中的相应的行,才能删除zb的行。