Oracle 用数组 遍历结果集 不用游标

61 篇文章 2 订阅
45 篇文章 7 订阅

下面的查询语句返回多条记录,into re,而re只是接收一条记录,所以报错。
 

declare
v_str varchar2(500);
type red is record
(
 v_id integer,
 v_name varchar2(30)
);
re red;
begin
v_str := 'select id,name from a1 ';
execute immediate v_str into re;
for i in 1..re.count loop
dbms_output.put_line(i.v_id||''||i.v_name);
end loop;
end;
 

应该将re声明为red类型的数组,加下面:

1

2

3

4

5

6

7

8

9

10

declare

type emp_type is table of emp%rowtype index by binary_integer;

emp_rec emp_type;

begin

     select * bulk collect into emp_rec from emp;

     for in 1..emp_rec.count loop

         dbms_output.put_line('empno='||emp_rec(i).empno||'; ename='||emp_rec(i).ename||'; job='||emp_rec(i).job||

                              '; mgr='||emp_rec(i).mgr);         

     end loop;

end;

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

declare 

v_str varchar2(500); 

type red is table of a1%rowtype index by binary_integer; 

re red; 

cur sys_refcursor;

i number:=1;

begin 

v_str := 'select id,name from a1 '

open cur for v_str;

loop

fetch cur into re(i);

exit when cur%notfound;

i:=i+1;

end loop;

close cur;

 

for in 1..re.count loop 

dbms_output.put_line(re(j).id||''||re(j).name); 

end loop; 

end

 

如果execute immediate执行的是结果集的话可以用
execute immediate v_sql bulk collect into 集合变量

declare 
type red is table of a1%rowtype index by binary_integer; 
re red; 
begin 
execute immediate 'select id,name from a1 ' bulk collect into re; 
for j in 1..re.count loop 
dbms_output.put_line(re(j).id||''||re(j).name); 
end loop; 
end; 

 

将原来的record 变成了表。 
type 名字 is record  只能放1条记录

type 名字 is record  是存放单行多列的数据

declare
v_str varchar2(500);
type red is table of a1%rowtype index by binary_integer;
re red;
begin
v_str := 'select id,name from a1 ';
execute immediate v_str bulk collect into re;
for i in re.first..re.count loop
dbms_output.put_line(re(i).id||''||re(i).name);
end loop;
end;

 

参考:https://bbs.csdn.net/topics/320130350

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值