Oracle:數據庫對象(一)

數據庫對象

一.創建對象

例如:

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);
發佈了180 篇原創文章 · 獲贊 335 · 訪問量 64萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章