ORACLE存储过程RECORD数据类型的使用

RECORD记录数据类型,是将多个基本数据类型变量组合成一个整体,作为一个复合数据类型使用

  • RECORD定义及使用
create or replace procedure zhzitywp.test is
--记录数据类型定义
type stu_record is record(
  id    integer      not null,
  name  varchar2(20) not null,
  score number(20,2) not null := 0
);
--声明记录数据类型变量
stu_record_val stu_record;
begin
  select id,name,score into stu_record_val from user where rowid = 1;
  dbms_output.put_line(stu_record_val.id);
  dbms_output.put_line(stu_record_val.name);
  dbms_output.put_line(stu_record_val.score);
end test;

需要注意的是,RECORD记录数据类型,仅能接收单行多列的查询结果,如果查询结果返回是多行就需要配合数组使用

  • RECORD搭配数组使用
create or replace procedure zhzitywp.test is
--记录数据类型定义
type stu_record is record(
  id    integer      not null,
  name  varchar2(20) not null,
  score number(20,2) not null := 0
);
--记录数据类型的数组定义
type stu_record_arr is table of stu_record;
--声明数组变量
stu_record_arr_val stu_record_arr ;
begin
  --查询结果是多行多字段,此处不能使用select into,而要用select bulk collect into
  select id,name,score bulk collect into stu_record_arr_val from user;
  --遍历查询结果,每行都是一个RECORD记录数据类型
  for i in 1 .. stu_record_arr_val.count loop
    begin
      dbms_output.put_line(stu_record_arr_val (i).id);
      dbms_output.put_line(stu_record_arr_val (i).name);
      dbms_output.put_line(stu_record_arr_val (i).score);
    end;
  end loop;
end test;

上面用到的bulk collect,可以减少loop开销,将查询结果一次性加载到collections中,适用于select into、fetch into、returning into等语句,且所有的into变量必须是collections