PLSQL中的記錄類型Record類似於C語言中的結構體,無非就是將若干相關聯的字段組合成一個整體,假設有如下的表格,使用自定義的Record類型將其讀取,它的使用方法歸納如下:
一、使用普通的數據類型定義Record
declare
TYPE mydept_type IS RECORD(
dnum number,
dname varchar2(20)
);
v_dept mydept_type;
begin
select deptnum,dname into v_dept from mydept where deptnum=1;
dbms_output.put_line(v_dept.dnum||'、'||v_dept.dname);
end;
/
二、使用“字段%type”的形式定義Record
declare
type mydept_type is record(
dnum mydept.deptnum%type,
dname mydept.dname%type
);
v_dept mydept_type;
begin
select * into v_dept from mydept where deptnum=1;
dbms_output.put_line(v_dept.dnum||'、'||v_dept.dname);
end;
/
三、利用Record類型向數據庫中插入數據
--利用Record類型向數據庫中插入數據
declare
type mydept_type is record(
dnum mydept.deptnum%type,
dname mydept.dname%type
);
v_dept mydept_type;
begin
v_dept.dnum := 2; --賦值語句一定要在begin塊中
v_dept.dname := 'TEST';
INSERT INTO mydept VALUES V_DEPT; --values後面直接跟着定義的record類型的變量
end;
/
四、利用Record類型向數據庫中修改數據
declare
type mydept_type is record(
dnum mydept.deptnum%type,
dname mydept.dname%type
);
v_dept mydept_type;
begin
v_dept.dnum := 2;
v_dept.dname := '軟件中試部';
update mydept set row = v_dept where deptnum=2; --使用關鍵字row
end;
/
五、Record和“表名%rowtype”
declare
v_dept mydept%rowtype;
begin
select * into v_dept from mydept where deptnum=1;
dbms_output.put_line(v_dept.deptnum||'、'||v_dept.dname);
end;
/
rowtype其實就是一種固定了字段的Record,而Record的靈活之處就在於可以由我們對字段進行自定義,比如利用一行中某幾個字段組成一個Record。