若創(chuàng)建 records,需要先定義一個(gè) RECORD 類型,再用該類型聲明變量。也可以創(chuàng)建或查找一個(gè)表、視圖,或 PL/SQL 游標(biāo),總之是你想
本文內(nèi)容
若創(chuàng)建 records,需要先定義一個(gè) RECORD 類型,再用該類型聲明變量。也可以創(chuàng)建或查找一個(gè)表、視圖,或 PL/SQL 游標(biāo),總之是你想要的值,使用 %ROWTYPE 屬性來(lái)創(chuàng)建匹配的 Record。
你可以在任何 PL/SQL 塊、子程序或包的聲明部分定義 RECORD 類型。當(dāng)你自定義 RECORD 類型時(shí),不能在域上指定一個(gè) NOT NULL 的約束,或給出它們的默認(rèn)值。
示例 1:演示聲明和初始化一個(gè)簡(jiǎn)單的 Record 類型
DECLARE TYPE DeptRecTyp IS RECORD ( deptid NUMBER(4) NOT NULL := 99, dname departments.department_name%TYPE, loc departments.location_id%TYPE, region regions%ROWTYPE ); dept_rec DeptRecTyp;BEGIN dept_rec.dname := 'PURCHASING';END;/
示例 2:演示聲明和初始化 Record 類型
:= -1, name VARCHAR2(64) NOT NULL := '[anonymous]');-- Declare record variables of the types declared rec1 rec1_t; rec2 rec2_t;-- Declare a record variable that can hold-- a row from the EMPLOYEES table.-- The fields of the record automatically match the names and-- types of the columns.-- Don't need a TYPE declaration in this case. rec3 employees%ROWTYPE;-- Or mix fields that are table columns with user-defined fields. TYPE rec4_t IS RECORD (first_name employees.first_name%TYPE, last_name employees.last_name%TYPE, rating NUMBER); rec4 rec4_t;BEGIN-- Read and write fields using dot notation rec1.field1 := 'Yesterday'; rec1.field2 := 65; rec1.field3 := TRUNC(SYSDATE-1);-- Didn't fill name field, so it takes default value DBMS_OUTPUT.PUT_LINE(rec2.name);END;/
若在數(shù)據(jù)庫(kù)存儲(chǔ)一個(gè) Record,你可以在 INSERT 或 UPDATE 語(yǔ)句指定,只要它的域與表的列匹配。
你可以使用 %TYPE 來(lái)指定 Record 域類型對(duì)應(yīng)表的列的類型。即使列類型改變了,你的代碼仍然可以運(yùn)行。例如,增加了 VARCHAR2 字段的長(zhǎng)度,或 NUMBER 字段的精度。
示例 3:演示使用 %ROWTYPE 來(lái)聲明一個(gè) Record,,來(lái)保存 department 表的信息
DECLARE-- Best: use %ROWTYPE instead of specifying each column.-- Use PL/SQL 可以定義包含對(duì)象、集合和其他 Record(內(nèi)置 Record)的 Record。但 Record 不能是對(duì)象類型的屬性。 若聲明一個(gè) Record,表示數(shù)據(jù)庫(kù)表的一行,則無(wú)需列出列,使用 %ROWTYPE 屬性。 當(dāng)表添加列后,你的代碼仍然可以運(yùn)行。若你想表示一個(gè)表列的一個(gè)子集,或是不同表的列,則你可以定義一個(gè)視圖或聲明一個(gè)游標(biāo),來(lái)選擇右邊的列,執(zhí)行任何需要的連接,再在視圖或游標(biāo)上應(yīng)用 %ROWTYPE。 聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com%ROWTYPE because -- you only want some columns.-- Declaring cursor doesn't run query or affect performance. CURSOR c1 IS
SELECT department_id, department_name, location_id
FROM departments; rec1 c1%ROWTYPE;-- Use
Oracle11gRelease1(11.1)PL/SQL_理解Record類型
最新推薦
猜你喜歡
熱門推薦