---
title: "Oracle Cursors语法总结"
author: "Ben.Sin"
date: "2012-05-03T17:50:20Z"
tags: []
categories: ["数据库"]
slug: "oracle-cursors"
draft: false
lastmod: "2012-05-03T17:50:20Z"
id: 1508973
url: "https://ben-sin.iteye.com/blog/1508973"
---

Oracle Cursors语法总结  
关于Oracle Cursors的语法总结，Oracle Cursors是用来查询数据库，获取记录集合（结果集）的指针，可以让开发者一次访问一行结果集，在每条结果集上作操作。

 

 

一．Oracle的Cursors概念：  
游标：用来查询数据库，获取记录集合（结果集）的指针，可以让开发者一次访问一行结果集，在每条结果集上作操作。

二．Oracle的Cursors分类：  
1．静态游标：  
分为显式游标和隐式游标。  
2．REF游标：  
是一种引用类型，类似于指针。

三．Oracle的Cursors详细内容：  
1．显式游标：  
CURSOR游标名(参数) \[返回值类型] IS  
Select语句  
生命周期：  
a.打开游标(OPEN)  
解析，绑定。。。不会从数据库检索数据  
b.从游标中获取记录(FETCH INTO)  
执行查询，返回结果集。通常定义局域变量作为从游标获取数据的缓冲区。  
c.关闭游标(CLOSE)  
完成游标处理，用户不能从游标中获取行。还可以重新打开。  
选项：参数和返回类型  
set serveroutput on  
declare  
cursor emp\_cur ( p\_deptid in number) is  
select * from employees where department\_id = p\_deptid;  
l\_emp employees%rowtype;  
begin  
dbms\_output.put\_line('Getting employees from department 30');  
open emp\_cur(30);  
loop  
  fetch emp\_cur into l\_emp;  
  exit when emp\_cur%notfound;  
  dbms\_output.put\_line('Employee id '|| l\_emp.employee\_id || ' is ');  
  dbms\_output.put\_line(l\_emp.first\_name || ' ' || l\_emp.last\_name);  
end loop;  
close emp\_cur;  
dbms\_output.put\_line('Getting employees from department 90');  
open emp\_cur(90);  
loop  
  fetch emp\_cur into l\_emp;  
  exit when emp\_cur%notfound;  
  dbms\_output.put\_line('Employee id '|| l\_emp.employee\_id || ' is ');  
  dbms\_output.put\_line(l\_emp.first\_name || ' ' || l\_emp.last\_name);  
end loop;  
close emp\_cur;  
end;  
/

2．隐式游标：  
不用明确建立游标变量，分两种：  
a.在PL/SQL中使用DML语言，使用ORACLE提供的名为SQL的隐示游标  
b.CURSOR FOR LOOP，用于for loop语句  
a.举例：  
declare  
begin  
update departments set department\_name=department\_name;  
\--where 1=2;

dbms\_output.put\_line('update '|| sql%rowcount ||' records');  
end;  
/

b.举例：  
declare  
begin  
for my\_dept\_rec in ( select department\_name, department\_id from departments)  
loop  
  dbms\_output.put\_line(my\_dept\_rec.department\_id || ' : ' || my\_dept\_rec.department\_name);  
end loop;  
end;  
/

c.举例：  
单独select  
declare  
l\_empno emp.EMPLOYEE\_ID%type;  
\-- l\_ename emp.ename%type;  
begin  
select EMPLOYEE\_ID    
  into l\_empno  
from emp;  
\--where rownum =1;  
dbms\_output.put\_line(l\_empno);  
end;  
/

使用INTO获取值，只能返回一行。

游标属性：  
%FOUND：变量最后从游标中获取记录的时候，在结果集中找到了记录。  
%NOTFOUND：变量最后从游标中获取记录的时候，在结果集中没有找到记录。  
%ROWCOUNT：当前时刻已经从游标中获取的记录数量。  
%ISOPEN：是否打开。  
Declare  
Cursor emps is  
Select * from employees where rownum&lt;6 order by 1;

Emp employees%rowtype;  
Row number :=1;  
Begin  
Open emps;  
Fetch emps into emp;

Loop  
  If emps%found then  
   Dbms\_output.put\_line('Looping over record '||row|| ' of ' || emps%rowcount);  
   Fetch emps into emp;  
   Row := row + 1;  
  Elsif emps%notfound then  
   Exit;  ---exit loop, not IF  
  End if;  
End loop;

If emps%isopen then  
  Close emps;  
End if;  
End;  
/

显式和隐式游标的区别：  
尽量使用隐式游标，避免编写附加的游标控制代码（声明，打开，获取，关闭），也不需要声明变量来保存从游标中获取的数据。

3．REF CURSOR游标：  
动态游标，在运行的时候才能确定游标使用的查询。分类：  
1．强类型（限制）REF CURSOR，规定返回类型  
2．弱类型（非限制）REF CURSOR，不规定返回类型，可以获取任何结果集。  
TYPE ref\_cursor\_name IS REF CURSOR \[RETURN return\_type]

Declare  
Type refcur\_t is ref cursor;

Type emp\_refcur\_t is ref cursor return employee%rowtype;  
Begin  
Null;  
End;  
/

强类型举例：  
declare  
\--声明记录类型  
type emp\_job\_rec is record(  
  employee\_id number,  
  employee\_name varchar2(50),  
  job\_title varchar2(30)  
);  
\--声明REF CURSOR，返回值为该记录类型  
type emp\_job\_refcur\_type is ref cursor  
  return emp\_job\_rec;  
\--定义REF CURSOR游标的变量  
emp\_refcur emp\_job\_refcur\_type;  
emp\_job emp\_job\_rec;  
begin  
open emp\_refcur for  
  select e.employee\_id,  
    e.first\_name || ' ' ||e.last\_name "employee\_name",  
    j.job\_title  
  from employees e, jobs j  
  where e.job\_id = j.job\_id and rownum &lt; 11 order by 1;  
fetch emp\_refcur into emp\_job;  
while emp\_refcur%found loop  
  dbms\_output.put\_line(emp\_job.employee\_name || '''s job is ');  
  dbms\_output.put\_line(emp\_job.job\_title);  
  fetch emp\_refcur into emp\_job;  
end loop;  
end;  
/