oracle游标cursor简单使用
总共介绍两种游标cursor 与 sys_refcursor
1、cursor游标使用
/*简单cursor游标 *students表里面有name字段,你可以换做其他表测试 */--定义declare --定义游标并且赋值(is 不能和cursor分开使用) cursor stus_cur is select * from students; --定义rowtype cur_stu students%rowtype; /*开始执行*/ begin --开启游标 open stus_cur; --loop循环 loop --循环条件 exit when stus_cur%notfound; --游标值赋值到rowtype fetch stus_cur into cur_stu; --输出 dbms_output.put_line(cur_stu.name); --结束循环 end loop; --关闭游标 close stus_cur; /*结束执行*/ end;
执行结果
SQL> declare 2 --定义游标并且赋值(is 不能和cursor分开使用) 3 cursor stus_cur is select * from students; 4 --定义rowtype 5 cur_stu students%rowtype; 6 /*开始执行*/ 7 begin 8 --开启游标 9 open stus_cur; 10 --loop循环 11 loop 12 --循环条件 13 exit when stus_cur%notfound; 14 --游标值赋值到rowtype 15 fetch stus_cur into cur_stu; 16 --输出 17 dbms_output.put_line(cur_stu.name); 18 --结束循环 19 end loop; 20 --关闭游标 21 close stus_cur; 22 /*结束执行*/ 23 end; 24 / 杨过郭靖付政委刘自飞江风任我行任盈盈令狐冲韦一笑张无忌朵儿谢逊小龙女欧阳锋欧阳锋
2、sys_refcursor游标使用
/* *游标名:sys_refcursor *特别注意赋值方式:for *与上重复内容不在叙述 */declare stu_cur sys_refcursor; stuone students%rowtype; begin --这句赋值方式for open stu_cur for select * from students; --fetch赋值给rowtype fetch stu_cur into stuone; loop dbms_output.put_line(stuone.name||' '||stuone.hobby); fetch stu_cur into stuone; exit when stu_cur%notfound; end loop; end;
执行结果
SQL> /* 2 *游标名:sys_refcursor 3 *特别注意赋值方式:for 4 *与上重复内容不在叙述 5 */ 6 declare 7 stu_cur sys_refcursor; 8 stuone students%rowtype; 9 10 begin 11 --这句赋值方式for 12 open stu_cur for select * from students; 13 --fetch赋值给rowtype 14 fetch stu_cur into stuone; 15 16 loop 17 dbms_output.put_line(stuone.name||' '||stuone.hobby); 18 fetch stu_cur into stuone; 19 exit when stu_cur%notfound; 20 end loop; 21 end; 22 / 杨过 保护小龙女郭靖 修炼降龙十八掌付政委 看小人书刘自飞 编程写代码江风 编程写代码任我行 修炼神功任盈盈 游山玩水令狐冲 行侠仗义韦一笑 吸拾人雪张无忌 修行朵儿 洗浴谢逊 毕生研究屠龙刀小龙女 修炼玉女心经欧阳锋 看小人书
补充一种循环条件
declare stu_cur sys_refcursor; stuone students%rowtype; begin open stu_cur for select * from students; fetch stu_cur into stuone; --特别注意循环条件的改变 --这个条件是发现了在循环 --与上一个notfound不同的 while stu_cur%found loop dbms_output.put_line(stuone.name||' '||stuone.hobby); fetch stu_cur into stuone; end loop; end;