Oracle级联操作

2014-11-24 18:05:38 · 作者: · 浏览: 0

1、SET NULL:


此关键字用于表示当删除主表中被引用列的数据时,将子表中相应引用列的值设置为NULL值。这种情况要求子表中的引用列支持NULL值。


2、CASCADE:


此关键字用于表示当删除主表中被引用列的数据时,级联删除子表中相应的数据行。


3、NO ACTION:


约束后面省略ON DELETE的情况,此关键字用于表示当删除主表中被引用列的数据时,如果子表的引用列中包含该值,则禁止该操作执行。


下面通过例子展示:


第一种情况:


--创建主表


SQL> create table father(


2 f_id number(10) primary key,


3 f_name varchar2(20)


4 );


表已创建。


--创建从表


SQL> create table child(
2 c_id number(10) primary key,
3 f_id number(10),
4 c_name varchar2(20),
5 constraint ch_fa foreign key (f_id) references father(f_id)
6 on delete set null
7 );

--插入数据


SQL> insert into father values (1,'cupid');


已创建 1 行。


SQL> insert into father values (2,'dorria');


已创建 1 行。


SQL> insert into child values (1,1,'jack');


已创建 1 行。


SQL> insert into child values (2,2,'rose');


已创建 1 行。


commit;


提交完成。


SQL> delete from father where f_id=1;


已删除 1 行。


SQL> commit;


提交完成。


SQL> select * from father;


F_ID F_NAME
---------- -------------------------------
2 dorria
SQL> select * from child;


C_ID F_ID C_NAME
---------- ---------- --------------------
1 jack
2 2 rose


第二种情况:


--创建主表


SQL> create table father_1(


2 f_id number(10) primary key,


3 f_name varchar2(20)


4 );


表已创建。


--创建从表


SQL> create table child_1(
2 c_id number(10) primary key,
3 f_id number(10),
4 c_name varchar2(20),
5 constraint ch_fa_1 foreign key (f_id) references father(f_id)
6 on delete cascade
7 );

--插入数据


SQL> insert into father_1 values (1,'cupid');


已创建 1 行。


SQL> insert into father_1 values (2,'dorria');


已创建 1 行。


SQL> insert into child_1 values (1,1,'jack');


已创建 1 行。


SQL> insert into child_1 values (2,2,'rose');


已创建 1 行。


commit;


提交完成。


SQL> delete from father where f_id=1;


已删除 1 行。


SQL> commit;


提交完成。


SQL> select * from father;


F_ID F_NAME
---------- -------------------------------
2 dorria
SQL> select * from child_1;


C_ID F_ID C_NAME
---------- ---------- --------------------
2 2 rose



第三种情况:


--创建主表


SQL> create table father_2(


2 f_id number(10) primary key,


3 f_name varchar2(20)


4 );


表已创建。


--创建从表


SQL> create table child_2(
2 c_id number(10) primary key,
3 f_id number(10),
4 c_name varchar2(20),
5 constraint ch_fa_2 foreign key (f_id) references father(f_id)
6 );

--插入数据


SQL> insert into father_2 values (1,'cupid');


已创建 1 行。


SQL> insert into father_2 values (2,'dorria');


已创建 1 行。


SQL> insert into child_2 values (1,1,'jack');


已创建 1 行。


SQL> insert into child_2 values (2,2,'rose');


已创建 1 行。


commit;


提交完成。


SQL> delete from father_2 where f_id=1;
delete from father_2 where f_id=1
*
第 1 行出现错误:
ORA-02292: 违反完整约束条件 (SCOTT.CH_FA_2) - 已找到子记录