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

基础:

首先是一般游标(cursor)定义方式:

cursor <cursor name> [(<list of parameters>)] is <select statement>;

其中的parameters会在selectstatment中用到。

<o:p> </o:p>

接着是有关于循环语句的使用,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.<o:p></o:p>

首先,while循环:

[<< <label name> >>]<o:p></o:p>

while <condition> loop<o:p></o:p>

<sequence of statements>;<o:p></o:p>

end loop [<label name>] ;

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

exit <label name>;

<o:p> </o:p>

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

[<< <label name> >>]<o:p></o:p>

for <index> in [reverse] <lower bound>..<upper bound> loop<o:p></o:p>

<sequence of statements><o:p></o:p>

end loop [<label name>] ;

这里的index可以视为一个for内部的常量(不可改变),并且,它还会覆盖外部同名的量(It overrides the scope of any variable having the same name outside the loop.<o:p></o:p>

)。<o:p></o:p>

reserve的意思是循环从upper bound 开始到lower bound

<o:p> </o:p>

知道了循环的基本知识,继续有关cursor使用的问题:

在程序体里,要使用cursor,首先是open:

open <cursor name> [(<list of parameters>)] ;

open之后,cursor定义时的select语句就已经被执行。而游标指向结果集中的第一个。这样,就可以用fetch获得结果:

fetch <cursor name> into <list of variables>;

每执行一次fetch,游标就移向结果集中的下一个。(这也就是需要用到循环语句的地方了)

最后需要做的是关闭游标:

close <cursor name>;

<o:p> </o:p>

另外,在循环里可以用exit退出:<o:p></o:p>

exit [<block label>] [when <condition>]

如果block label没有写,那么就结束最近的循环。而condition里也可以写一些简单的条件值,比如<cursor name>%NOTFOUND<cursor name>%FOUND%ROWCOUNT%ISOPEN等。<o:p></o:p>

<o:p> </o:p>

forcursor结合使用,可以写成:<o:p></o:p>

[<< <label name> >>]<o:p></o:p>

for <record name> in <cursor name>[(<list of parameters>)] loop<o:p></o:p>

<sequence of statements><o:p></o:p>

end loop [<label name>];<o:p></o:p>

 

<o:p> </o:p>

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

[<< <label name> >>]<o:p></o:p>

for <record name> in <cursor name>[(<list of parameters>)] loop<o:p></o:p>

<sequence of statements><o:p></o:p>

end loop [<label name>];

比如:<o:p></o:p>

for sal_rec in (select SAL + COMM total from EMP) loop<o:p></o:p>

. . . ;<o:p></o:p>

end loop;

注意上面斜体的别名total算是一个小技巧,以后要调用结果集,就可以使用sal_rec.total的形式。<o:p></o:p>

  这个语句已经自动包括了cursoropen, close等操作,并且,在没有数据的情况下,其自动调用exit<o:p></o:p>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值