oracle级联更新与级联删除

Oracle级联删除:可以使用外键约束来实现,建立表的主外键关系,给列设置级联删除。如下:

——创建了CLASS表,并设置ID字段为主键。

复制代码
-- Create table
create table CLASS
(
ID VARCHAR2(2) not null,
CLASS_NAME VARCHAR2(20)
)
alter table CLASS
add constraint PK_CLASS primary key (ID)
复制代码

——创建了STUDENTS表,并设置ID字段为主键,CLASS_ID为外键且有级联删除。

复制代码
-- Create table
create table STUDENTS
(
ID VARCHAR2(4) not null,
CLASS_ID VARCHAR2(2) not null,
STU_NAME VARCHAR2(20),
STU_AGE NUMBER
)

alter table STUDENTS
add constraint PK_STU primary key (ID)

alter table STUDENTS
add constraint FK_STU foreign key (CLASS_ID)
references CLASS (ID) on delete cascade;
复制代码

这样删除了班级ID,所属的学生都会被删除。(转自https://www.cnblogs.com/milo-xie/archive/2011/07/17/2108939.html)

级联更新:只能使用触发器来实现,如下:

--首先创建实例表book和type
create table type(
tid number(4) primary key,
tname varchar2(10) not null
)
/
create table book(
bid number(4) primary key,
bname varchar2(20) not null,
tid number(4),
)
/
--建立外键约束
alter table book add constraint book_type foreign key(tid) references type(tid);
--插入测试数据
insert into type values(1,'历史');
insert into type values(2,'文学');
insert into book values(1,'红楼梦',2);
insert into book values(2,'西游记',2);
select * from type;
select * from book;
--创建级联更新触发器
create or replace trigger tri_type
after update of tid on type
for each row
begin
if(:old.tid<>:new.tid) then
update book set tid=:new.tid where tid=:old.tid;
end if;
end;
--进行更新操作,测试触发器是否起作用
update type set tid=3 where tid=2;

(转自http://blog.sina.com.cn/s/blog_8e5087d10102wgh6.html)

原文地址:https://www.cnblogs.com/xiaoyuersdch/p/8274684.html