1.什么是游标
游标是系统为用户开设的一个数据缓冲区,存放SQL语句的执行结果。我们可以
在声明区声明游标,语法如下:
cursor 游标名称 is SQL语句; |
使用游标语法
open 游标名称 loop fetch 游标名称 into 变量 exit when 游标名称%notfound end loop; close 游标名称 |
把游标理解为PL/SQL中的结果集。
1.1无参数游标
需求:打印业主类型为1的价格表
代码:
declare v_pricetable T_PRICETABLE%rowtype;--价格行对象 cursor cur_pricetable is select * from T_PRICETABLE where ownertypeid=1;--定义游标 begin open cur_pricetable;--打开游标 loop fetch cur_pricetable into v_pricetable;--提取游标到变量 exit when cur_pricetable%notfound;--当游标到最后一行下面退出循环 dbms_output.put_line( '价格:' ||v_pricetable.price ||'吨位:'||v_pricetable.minnum||'-'||v_pricetable.maxnum ); end loop; close cur_pricetable;--关闭游标 end ; |
运行结果如下:
1.2带参数的游标
我们的查询语句的条件值有可能是在运行时才能决定的,比如业主类型,可能是运行时才可以决定,那如何实现呢?我们接下来学习带参数的游标,修改上述案例
declare v_pricetable T_PRICETABLE%rowtype;--价格行对象 cursor cur_pricetable(v_ownertypeid number) is select * from T_PRICETABLE where ownertypeid=v_ownertypeid;--定义游标 begin open cur_pricetable(2);--打开游标 loop fetch cur_pricetable into v_pricetable;--提取游标到变量 exit when cur_pricetable%notfound;--当游标到最后一行下面退出循环 dbms_output.put_line('价格:'||v_pricetable.price ||'吨位:'||v_pricetable.minnum||'-'||v_pricetable.maxnum ); end loop; close cur_pricetable;--关闭游标 end ; |
1.3for循环提取游标值
我们每次提取游标,需要打开游标 关闭游标 循环游标 提取游标 控制循环的退出等等,好麻烦!有没有更简单的写法呢?有!用for循环一切都那么简单,上例的代码可以改造为下列形式
declare cursor cur_pricetable(v_ownertypeid number) is select * from T_PRICETABLE where ownertypeid=v_ownertypeid;--定义游标 begin for v_pricetable in cur_pricetable(3) loop dbms_output.put_line('价格:'||v_pricetable.price ||'吨位:'||v_pricetable.minnum||'-'||v_pricetable.maxnum ); end loop; end ; |