关于delete cascade的小实验
创建用于测试的三张表test_a,test_b,test_c
create table test_a(id int not null, fk int, constraint pk primary key(id));
create table test_b(id int not null, fk int, constraint pe primary key(id));
create table test_c(id int not null, fk int, constraint pr primary key(id));
ID主键,在FK列上建立外键
插入测试数据
insert into test_a values(1,11);
insert into test_a values(2,22);
insert into test_b values(11,1);
insert into test_b values(22,2);
insert into test_c values(111,11);
insert into test_c values(222,22);
commit;
在test_b和test_c上建立外键约束
alter table test_b add constraint fk_test_b foreign key (fk) references test_a(id) on delete cascade;
alter table test_c add constraint fk_test_c foreign key (fk) references test_b(id) on delete cascade;
从test_a级联删除id为1的行
delete from test_a where id=1;
成功
需要说明的是
1、如果仅仅在test_b上建立 on delete cascade 选项,则会出现在test_c上无法删除的情况,因此不能成功
2、在测试过程中,如果使用truncate截断test_a,或者test_b会出现orc-02266的情况,必须使用alter table test_b disable constraint fk_test_b;
alter table test_b disable primary key; 但是在此时会出现另一个错误,ora-02297,因为test_c的fk_test_c依赖test_b(id)主键,因此需要先
alter table test_c disable constrait fk_test_c;
3、查阅相关的资料发现Oracle没有on update cascad 选项,参阅http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5773459616034
外键作为数据库参照完整性的原则,其目的就是为了使相关联的表之间保证完整,如建立约束时没有指定on delete cascade 选项,则应该从子表依次删除以保证参照实体的完整,如果未指定,默认应该是NO ACTION;
[@more@]来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/9236282/viewspace-1029890/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/9236282/viewspace-1029890/