数据库对象
一.创建对象
例如:
create type t_address as object (
street varchar(15),
city varchar(15),
state char(2),
zip varchar(5)
);
属性的本身也可以是对象类型
create type t_person as object (
id integer,
first_name varchar(10),
last_name varchar(10),
dob date,
phone varchar(12),
address t_address
);
使用member function子句声明一个名为get_sell_by_date函数
create type t_product as object (
id integer,
name varchar2(15),
description varchar2(22),
price number(5, 2),
days_valid integer,
member function get_sell_by_date return date
);
create type body t_product as
member function get_sell_by_date return date is
v_sell_by_date date;
begin
select days_valid + sysdate
into v_sell_by_date
from dual;
return v_sell_by_date;
end;
end;
创建同义词,使得所有用户都可以看到t_product类型。
create public synonym t_pub_product for t_product;
二.使用describe获取有关对象类型的信息
describe t_address
describe t_person
describe t_product
set describe depth 可以设置describe显示信息的深度
set describe depth 2 describe t_person
三.在数据表中使用对象类型
1.列对象
create table products (
product t_product,
quantity_in_stock integer
);
select p.product
from products p
where p.product.id = 1;
2.对象表
使用对象类型定义整个表,这样的表称为对象表
create table object_products of t_product;
select value(op) from object_products op;
3.对象标识符和对象引用
对象表中每个对象都具有唯一的对象标识符(OID),可以使用REF()函数检索对象的OID。
select ref(oc) from object_products op where op.id = 1;
OID存储在对象引用中,就可以访问引用对象。
可以使用REF类型定义对象引用
create table purchases (
id integer primary key,
product_ref ref t_product scope is object_products
);
scope is 子句将对象引用限制为指向特定表中的对象。
使用deref()函数检索存储在对象引用中的实际对象
select deref(product_ref)
from purchases;
四.比较对象值
select op.id, op.name, op.price, op.days_valid
from object_products op
where value(op) = t_product(1, 'pasta', '20 oz bag of pasta', 3.95, 10);