---
title: "oracle下巧用bulk collect实现cursor批量fetch"
author: "fanth"
date: "2011-02-16T20:26:35Z"
tags: []
categories: ["数据库"]
slug: "oracle-bulk-collect-cursor-fetch"
draft: false
lastmod: "2011-02-16T20:26:35Z"
id: 908162
url: "https://fanth.iteye.com/blog/908162"
---

declare

　　cursor c1 is select * from t\_depart;

　　v\_depart t\_depart%rowtype ;

　　type v\_code\_type is table of t\_depart.depart\_code%type ;

　　v\_code v\_code\_type ;

　　type v\_name\_type is table of t\_depart.depart\_name%type ;

　　v\_name v\_name\_type ;

　　begin

　　open c1;

　　fetch c1 bulk collect into v\_code , v\_name ;

　　for i in 1..v\_code.count loop

　　dbms\_output.put\_line(v\_code(i)||' '||v\_name(i));

　　end loop;

　　close c1;

　　end;

　　通过上面的这个列子大家可以发现如果列很多的话，为每一列定义一个集合似乎有些繁琐，可以把集合和%rowtype结合起来一起使用简化程序！

　　复制代码 代码如下:

　　declare

　　cursor c1 is select * from t\_depart;

　　type v\_depart\_type is table of t\_depart%rowtype ;

　　v\_depart v\_depart\_type ;

　　begin

　　open c1;

　　fetch c1 bulk collect into v\_depart ;

　　for i in 1..v\_depart.count loop

　　dbms\_output.put\_line(v\_depart(i).depart\_code||' '||

　　v\_depart(i).depart\_name);

　　end loop;

　　close c1;

　　end;

　　在输出结果时既可以使用集合的count属性和可以使用first和last，在引用%rowtype类型的内容时还有一个需要注意的地方是 v\_depart(i).depart\_code，而不是v\_depart.depart\_code(i),当然没有这样的写法，即使有意义也并不一样。

　　复制代码 代码如下:

　　declare

　　cursor c1 is select * from t\_depart;

　　type v\_depart\_type is table of t\_depart%rowtype ;

　　v\_depart v\_depart\_type ;

　　begin

　　open c1;

　　fetch c1 bulk collect into v\_depart ;

　　for i in v\_depart.first..v\_depart.last loop

　　dbms\_output.put\_line(v\_depart(i).depart\_code||' '||

　　v\_depart(i).depart\_name);

　　end loop;

　　close c1;

　　end;