您的位置:首页 > 数据库 > Oracle

Oracle Procedure (PL/SQL) 实践归纳(2)之Cursor的使用

2006-07-25 09:21 676 查看
基础:
首先是一般游标(cursor)定义方式:
cursor <cursor name> [(<list of parameters>)] is <select statement>;
其中的parameters会在selectstatment中用到。

接着是有关于循环语句的使用,Oracle Tutorial里说:
“PL/SQL provides while-loops, two types of for-loops, and continuous loops. Latter ones are used in combination with cursors. All types of loops are used to execute a sequence of statements multiple times.”
首先,while循环:

[<< <label name> >>]
while <condition> loop
<sequence of statements>;
end loop [<label name>] ;

其中,label name主要是用来在exit的时候选择要跳出的循环的:
exit <label name>;

然后是for循环,它与while的区别在于其可以控制循环次数:

[<< <label name> >>]
for <index> in [reverse] <lower bound>..<upper bound> loop
<sequence of statements>
end loop [<label name>] ;

这里的index可以视为一个for内部的常量(不可改变),并且,它还会覆盖外部同名的量(It overrides the scope of any variable having the same name outside the loop.
)。
reserve的意思是循环从upper bound 开始到lower bound。

知道了循环的基本知识,继续有关cursor使用的问题:
在程序体里,要使用cursor,首先是open:
open <cursor name> [(<list of parameters>)] ;
open之后,cursor定义时的select语句就已经被执行。而游标指向结果集中的第一个。这样,就可以用fetch获得结果:
fetch <cursor name> into <list of variables>;
每执行一次fetch,游标就移向结果集中的下一个。(这也就是需要用到循环语句的地方了)
最后需要做的是关闭游标:
close <cursor name>;

另外,在循环里可以用exit退出:
exit [<block label>] [when <condition>]
如果block label没有写,那么就结束最近的循环。而condition里也可以写一些简单的条件值,比如<cursor name>%NOTFOUND,<cursor name>%FOUND,%ROWCOUNT,%ISOPEN等。

将for与cursor结合使用,可以写成:

[<< <label name> >>]
for <record name> in <cursor name>[(<list of parameters>)] loop
<sequence of statements>
end loop [<label name>];

如果发现定义cursor比较麻烦,还可以在for里直接写select函数:

[<< <label name> >>]
for <record name> in <cursor name>[(<list of parameters>)] loop
<sequence of statements>
end loop [<label name>];

比如:

for sal_rec in (select SAL + COMM total from EMP) loop
. . . ;
end loop;

注意上面斜体的别名total算是一个小技巧,以后要调用结果集,就可以使用sal_rec.total的形式。
这个语句已经自动包括了cursor的open, close等操作,并且,在没有数据的情况下,其自动调用exit。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: