oracle嵌套表示例
--嵌套表:就是把一个表中的字段定义为一个表,这个字段表的数据存储在外部的一个表中,例如下例嵌套表中的数据存储在required_tab表中。
--嵌套表可以有效地代替多个表之间的连接
create type bookobj as object(
title varchar2(40),
author varchar2(40),
catalog_number number(4)
);
--定义一个嵌套表,该表可以被嵌套在其他表中,他的字段就是bookobj中的字段
create type booklist as table of bookobj;
create table course_material(
department char(3),
course number(3),
required_reading booklist --在表中再定义一个表,即booklist表,他就是嵌套在course_material中的表,也就是嵌套表。
--他和主表course_material之间是主从关系,即一条主表记录对应一个嵌套表中的多条记录。
) nested table required_reading store as required_tab;
--给表和嵌套表输入值,commit后被提交到数据库里保存
declare
v_books booklist:=booklist(bookobj('ssss','www',444)); --定义一个booklist类型的嵌套表变量v_books,并给出初值。
begin
insert into course_material values('cs',101,booklist(bookobj('www','bbb',1),bookobj('aa','dd',33)));
insert into course_material values('his',301,v_books);
end;
或单独插入一条记录:
insert into course_material values('ss',102,booklist(bookobj('w','b',1),bookobj('a','d',3)));
--更新嵌套表操作,即将required_reading作为一个字段
declare
v_books booklist:=booklist(bookobj('xyz','bbb',111),bookobj('zq','ccc',222));
begin
update course_material
set required_reading = v_books
where department = 'his' and course = 301;
end;
--执行结果为子记录全部被删除,新添加两个bookobj记录
--删除嵌套表中的记录
delete from course_material where department = 'his';--对应主表his的嵌套表中的记录将被删除
=============直接对嵌套表进行插入==================
insert into the(select required_reading from course_material where department='his' )
values('gog','ggg',999)
--上面红色的表示一个表,注意前面必须加上the,表示是嵌套表。
=============直接对嵌套表进行更新==================
update the(select required_reading from course_material where department='his' )
set catalog_number = catalog_number + 10 --对嵌套表中的字段进行操作
where catalog_number = 111;
=============直接对嵌套表进行删除==================
delete from the(select required_reading from course_material where department='his' )
where catalog_number = 111;
=========================直接进行嵌套表的查询,只能返回主表的一条记录的子表,即如果course_material返回多于2条的记录则报错
select * from the(select required_reading from course_material where department='his');
或
select * from the(select required_reading from course_material where department='his')
where catalog_number=999
报错:select * from the(select required_reading from course_material
where department in ('his','www'));
转载自:http://www.cnblogs.com/starzhao/archive/2010/05/19/1739234.html