北大青鸟oracle学习笔记13

来源:互联网 发布:a星寻路算法c 编辑:程序博客网 时间:2024/05/29 08:39

嵌套表:

 

与可变数组类似,不同之处是嵌套表没有数据上限。

语法:

 

创建基类型

create or replace type 嵌套表基类型名 as object(字段参数);

create or replace type mingxitype as object(

goodsid varchar(15),

incount int,

providerid varchar(10)

)not final;

 

创建嵌套表类型

create or replace type 嵌套表类型名 as table of 类型名;

create or replace type nestmingxitype as table of mingxitype;

 

创建表

create table 主表名(

字段1 类型,

字段2 类型,

...

字段n 类型,

嵌套类型字段 嵌套表类型名

)nested table 嵌套类型字段名 store as 真正存储的嵌套表;

create table instock

(

orderid varchar(13) not null primary key,

indate date,

mingxi nestmingxitype

)nested table mingxi store as mingxitable;

 

这里我想访问实际存储的表mingxitable,结果oracle报错如下:

cannot reference nested table column's storage table

看来想看看是不行了

 

添加数据:

insert into 主表名 [(字段列表)] values(

基本参数列表,

嵌套表类型名(嵌套表基类型名(参数列表))

);

insert into instock values(

'200200060001',

to_date('2002-08-06','yyyy-mm-dd'),

nestmingxitype(

mingxitype('j001',200,'1001'),

mingxitype('s001',1000,'1002'),

mingxitype('t005',500,'1003')

)

);

 

更新嵌套表数据:

更新嵌套表时并不用像更新可变数组一样更新全部数据,可以更新制定数据。

update table(select t.mingxi from instock t where orderid = 1002) mx

set mx.incount = 500

where mx.goodid='10001';

 

查询嵌套表中数据:

select * from table(select p.mingxi from instock where orderid = '200200060001');

 

删除嵌套表数据:

delete from table(select t.mingxi from instock t where orderid = '200200060001') t

where t.goodsid='j0001';

 

 

总之,使用table()函数将嵌套表看作一张普通的表,操作时候将函数嵌套到sql语句中即可。

 

 

 

 

对象表:

表中每一行都代表一个对象

包含对象标识符 OID

REF操作符用于引用行对象

DEREF操作符用户返回行对象的值

 

例:

创建科室类型

 

create or replace type officetype as object(

  id varchar(10),

  typename varchar(10)

);

 

通过科室类型创建科室表

create table offic of officetype;

插入数据

 

 

insert into office values (officetype('1','office1'));

insert into office values (officetype('2','office2'));

insert into office values (officetype('3','office3'));

 

 

获取OID值

在sql developer中显示不出来OID,而在sqlplus中可以显示。

select ref(o) from office o;

对象表中也有rowid,不过是产生的伪rowid。

select rowid from office;

 

对象的OID可以当作外键引用

人事表

 

create table worker(

  workerid varchar(10) primary key,

  workername varchar(10),

  workeroffice ref officetype scope is office -- scope约束workeroffice的值在office表范围中

);

 

使用子查询插入新员工

 

insert into worker select '1','worker1',ref(o)

  from office o where o.id = '1';

 

 

使用deref根据OID产生对象

select deref(w.workeroffice) from worker w;

返回 OFFICETYPE(1,office1)

 

查询对象表的时候使用value函数可以查询对象结果

select value(o) from office o;

返回

OFFICETYPE(1,office1)        

OFFICETYPE(2,office2)   

OFFICETYPE(3,office3) 

 

 

 

对象视图:

将关系表以对象表的形式使用

create view officeview of officetype with object oid(id) --将原来关系表中的id列值转换为oid使用

as select * from office;

 

make_ref(视图名,转换为OID的字段名) 可以引用到视图中的OID值。