Oracle级联删除:可以使用外键约束来实现,建立表的主外键关系,给列设置级联删除。如下:
——创建了CLASS表,并设置ID字段为主键。
--Create tablecreatetableCLASS
(
ID VARCHAR2(2) notnull,
CLASS_NAME VARCHAR2(20)
)
altertableCLASS
addconstraintPK_CLASS primarykey(ID)
——创建了STUDENTS表,并设置ID字段为主键,CLASS_ID为外键且有级联删除。
--Create tablecreatetableSTUDENTS
(
ID VARCHAR2(4) notnull,
CLASS_ID VARCHAR2(2) notnull,
STU_NAME VARCHAR2(20),
STU_AGE NUMBER)
altertableSTUDENTS
addconstraintPK_STU primarykey(ID)
altertableSTUDENTS
addconstraintFK_STU foreignkey(CLASS_ID)
referencesCLASS (ID) ondeletecascade;
这样删除了班级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)