oracle游标

游标基本语法

-- 创建游标语法:
-- cursor  游标名称  is   SQL语句;
-- 使用游标语法:
-- open 游标名称
-- loop
--   业务逻辑
-- fetch 游标名称  into 变量
-- exit   when   游标名称%notfound
--   业务逻辑
-- end loop;
-- close 游标名称

数据准备

create table t_pricetable
(
    id          number primary key,
    price       number(10, 2),
    ownertypeid number,
    minnum      number,
    maxnum      number
);
insert into t_pricetable
values (1, 2.45, 1, 0, 5);
insert into t_pricetable
values (2, 3.45, 1, 5, 10);
insert into t_pricetable
values (3, 4.45, 1, 10, null);

有参数游标

declare
    -- 声明行变量 v_pricetable
      v_pricetable t_pricetable%rowtype;
    -- 声明游标 cur_pricetable 保存业主类型为 1 的价格表 <cursor 游标名称 is SQL语句;>
      cursor cur_pricetable is
      select * from t_pricetable where ownertypeid=1;
begin
    -- 打开游标
     open cur_pricetable;
    -- loop 循环
     loop
         -- fetch 游标 into 变量 提取游标到变量
         fetch cur_pricetable into v_pricetable;
         -- 当游标到最后一行下面退出循环 exit when 游标%notfound;
         exit when cur_pricetable%notfound;
         -- 输出 价格: XX, 吨位: YY-ZZ
         DBMS_OUTPUT.PUT_LINE('价格:'||v_pricetable.price||'吨位:'||v_pricetable.minnum||v_pricetable.maxnum);
     end loop;
    -- 关闭游标
     close cur_pricetable;
end;

无参数游标

declare
    -- 声明行变量 v_pricetable
      v_pricetable t_pricetable%rowtype;
    -- 声明有参数的游标 cur_pricetable(变量名 类型) 保存业主类型为 1 的价格表 <cursor 游标名称 is SQL语句;>
      cursor cur_pricetable(o_type number) is
      select * from t_pricetable where ownertypeid=o_type;
begin
    -- 打开游标(传入参数)
     open cur_pricetable(2);
     loop
         -- fetch 游标 into 变量 提取游标到变量
         fetch cur_pricetable into v_pricetable;
         -- exit when 游标%notfound;
         exit when cur_pricetable%notfound;
         DBMS_OUTPUT.PUT_LINE('价格:'||v_pricetable.price||'吨位:'||v_pricetable.minnum||v_pricetable.maxnum);
     end loop;
     -- 关闭游标
     close cur_pricetable;
end;

for 简化游标使用


declare
    -- 声明带参数游标 cur_pricetable 根据参数值获取指定类型的价格表
    cursor cur_pricetable(o_type number) is
    select * from t_pricetable where ownertypeid=o_type;
begin
    -- 使用 for 循环遍历
    for i in cur_pricetable(1) loop
        -- 打印 价格: XX, 吨位: YY-ZZ
        DBMS_OUTPUT.PUT_LINE('价格:'||i.PRICE||', 吨位:'||i.MINNUM||'--'||i.MAXNUM);
        end loop;
end;
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值