oracle数据库之游标

/*
 游标
 CURSOR 游标名[(参数1 数据类型[,参数2 数据类型...])] IS SELECT语句;
 开发步骤
     声明游标
     打开游标  open 游标名
     提取数据  fetch 游标名 into 记录名(变量)
                     游标名%found  发现记录
                     游标名%notfound  没有发现数据
     关闭游标  close 游标名
     
  系统引用游标
     声明游标  游标名 sys_refcursor;
     打开游标  open 游标名 for select *
     提取数据
     关闭游标
*/
-- 查询emp所有数据,不带参数
declare
  cursor ybs is select * from emp;
  yb emp%rowtype;
begin
  open ybs;
    loop 
    fetch ybs into yb;  
    exit when ybs%notfound;
    dbms_output.put_line(yb.ename||'.'||yb.job||'.'||yb.sal);
    end loop;
  close ybs;

end;

-- 查询部门为20 带参数
declare
  cursor ybs(dno number) is select * from emp where deptno = dno;
  yb emp%rowtype;
begin
  open ybs(20);   -- 开启游标,指定查询20号
    loop 
    fetch ybs into yb;  
    exit when ybs%notfound;
    dbms_output.put_line(yb.ename||'.'||yb.job||'.'||yb.sal);
    end loop;
  close ybs;
end;

-- 使用系统引用游标

declare
   ybs sys_refcursor;
  yb emp%rowtype; 
begin
  open ybs for select * from emp;
  loop
    fetch ybs into yb;
    exit when ybs%notfound;
    dbms_output.put_line(yb.job||'.'||yb.sal);
  end loop;
  
  close ybs;
  
end;



-- 使用for循环  接收游标数据
declare
  cursor ybs(dno number) is select * from emp where deptno = dno;
begin
  for yb in ybs(20) loop
     dbms_output.put_line(yb.job||'.'||yb.sal);
  end loop;
end;


/*
  更新工资小案例   总裁1000 经理800 其他400 emp表
*/

declare
  -- 创建游戏包含emp所有用户
  cursor ybs is select * from emp;
  yb emp%rowtype;   -- 定义变量
begin
  -- 打开游标
  open ybs;
  -- 循环提出数据
  loop
    fetch ybs into yb;
    exit when ybs%notfound;
      -- 分条件进行更新数据  总裁1000 经理800 其他400 emp表
    if yb.job='PRESIDENT' then   
      update emp set sal = sal + 1000 where empno = yb.empno;
    elsif  yb.job='MANAGER' then 
      update emp set sal = sal + 800 where empno = yb.empno;
    else
      update emp set sal = sal + 400 where empno = yb.empno;
    end if;
  end loop;
  --关闭游标
  close ybs;
  -- 提交事务
  commit;
end;

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值