Oracle的游标

2025-11-13 17:02:28

1、Oracle中的游标与Java中的迭代器有所区别,作为迭代器,开始时指向首元素之前,遍历后,指向尾元素之后;游标打开后,指向首行记录;

declare

--1、声明游标;

cursor cc is select ename,sal from emp;  

name emp.ename%type;

salary emp.sal%type;

begin

--2、打开游标;

open cc;

--3、使用游标;

fetch cc into name,salary;

show('name: '||name||',salary: '||salary);

--4、关闭游标;

close cc;

end;

/

Oracle的游标

2、游标的属性;

1、 cursor%found;存在记录;

2、 cursor%notfound;不存在记录;

3、 cursor%rowcount;当前遍历到第几行;

4、 cursor%isopen;是否打开;

Oracle的游标

3、遍历;

declare

--1、声明游标;

cursor cc is select ename,sal from emp;  

name emp.ename%type;

salary emp.sal%type;

begin

--2、打开游标;

open cc;

--3、使用游标;

loop

exit when cc%notfound;

fetch cc into name,salary;

show(''||cc%rowcount);

show('name: '||name||',salary: '||salary);

end loop;

--4、关闭游标;

close cc;

end;

/

Oracle的游标

4、另一种使用游标遍历表的形式,用for循环,在使用for遍历时,游标不需要显式的打开和关闭;在这种情况下,我们将游标看作“数组或集合”,用一个游标变量作为“元素”来执行;

declare

--声明游标;

cursor cc is select ename,sal from emp;

begin

for c in cc loop

show('ename: '||c.ename||', sal: '||c.sal);

end loop;

end;

/

Oracle的游标

5、当用游标使用for循环遍历表时,将游标当作集合来用,而循环中的临时变量作为每行记录使用;

declare

--声明游标;

cursor cc is select * from emp;

begin

for c in cc loop

show(''||c.hiredate||','||c.deptno||','||c.sal);

end loop;

end;

/

Oracle的游标

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢