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)

