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;/
2、游标的属性;1、cursor%found;存在记录;2、cursor%notfound;不存在记录;3、cursor%rowcount;当前遍历到第几行;4、cursor%isopen;是否打开;
3、遍历;declare--1、声明游标;cursor cc i衡痕贤伎s select ename,sal from emp; name emp.髫潋啜缅ename%type;salary emp.sal%type;begin--2、打开游标;open cc;--3、使用游标;loopexit when cc%notfound;fetch cc into name,salary;show(''||cc%rowcount);show('name: '||name||',salary: '||salary);end loop;--4、关闭游标;close cc;end;/
4、另一种使用游标遍历表的形式,用for循环,在使用for遍历时,游标不需要显式的打开和关闭;在这种情况下,我们将游标看作“数组或集合”,用一个游标变量作为“元素”来执行;declare--声明游标;cursor cc is select ename,sal from emp;beginfor c in cc loopshow('ename: '||c.ename||', sal: '||c.sal);end loop;end;/
5、当用游标使用for循环遍历表时,将游标当作集合来用,而循环中的临时变量作为每行记录使用;declare--声明游标;cursor cc is select * from emp;beginfor c in cc loopshow(''||c.hiredate||','||c.deptno||','||c.sal);end loop;end;/