5.游标

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 ;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值