基础:
首先是一般游标(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>
将for与cursor结合使用,可以写成:<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>
这个语句已经自动包括了cursor的open, close等操作,并且,在没有数据的情况下,其自动调用exit。<o:p></o:p>