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”
之前使用过下面的方法获取过mydept的数据
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。