oracle(38)_PL/SQL_ 游标 Cursor

版权声明:如需转载,请注明出处 https://blog.csdn.net/qq_36260974/article/details/89053533

PL/SQL

游标 Cursor

游标 Cursor
  • 在写 java 程序中有集合的概念,那么在 pl/sql 中也会用到多条记录,这时候我们就要用到游标,游标可以存储查询返回的多条数据。
  • 语法:
    CURSOR 游标名 [ (参数名  数据类型,参数名 数据类型,...)] IS SELECT 语句;
    

游标的使用步骤

  • 打开游标:open c1; (打开游标执行查询)
  • 取一行游标的值:fetch c1 into pjob; (取一行到变量中)
  • 关闭游标:close c1; (关闭游标释放资源)
  • 游标的结束方式 exit when c1%notfound
  • 注意:上面的 pjob 必须与 emp 表中的 job 列类型一致

范例:使用游标方式输出 emp 表中的员工编号和姓名

  • 示例图:
    在这里插入图片描述
    在这里插入图片描述

范例:按员工的工种长工资,总裁1000元,经理长800元其,他人员长400元

  • 示例图:
    在这里插入图片描述

范例:写一段 PL/SQL 程序,为部门号为 10 的员工涨工资

  • 示例图:
    在这里插入图片描述

● 以上操作完整源码:

--使用游标方式输出 emp 表中的员工编号和姓名
declare
  cursor c1 is
    select * from emp; --定义游标
  prec emp%rowtype; --定义记录型的变量
  
begin
  open c1; --打开游标
  loop
    fetch c1
      into prec; --从游标中取值,取值后游标会自动向下移动一步
    exit when c1%notfound;
    dbms_output.put_line(prec.empno || ' ' || prec.ename);
  end loop; --结束循环
  close c1; --关闭游标
end;

--按员工的工种长工资,总裁1000元,经理长800元其,他人员长400元。 
select * from myemp;
declare
  prec myemp%rowtype;
  cursor c1 is
    select * from myemp;
  addsal number(4);

begin
  --打开游标
  open c1;
  loop
    fetch c1
      into prec;
    exit when c1%notfound;
    if prec.job = 'PRESIDENT' then
      addsal := 1000;
    elsif prec.job = 'MANAGER' then
      addsal := 800;
    else
      addsal := 400;
    end if;
    update myemp t set t.sal = t.sal + addsal where t.empno = prec.empno;
  end loop;
  --关闭游标
  close c1;
  commit;--提交
end;

--带有参数的游标
--写一段PL/SQL程序,为部门号为10的员工涨工资。
select * from myemp t where t.deptno = 10;
declare
  cursor c1(dno myemp.deptno%type) is
    select * from myemp t where t.deptno = dno;
  prec myemp%rowtype;
  
begin
  --打开带有参数游标,除了此处其他的地方游标都不用带参数
  open c1(10);
  loop
    fetch c1
      into prec;
    exit when c1%notfound;
    update myemp t set t.sal = t.sal + 1000 where t.empno = prec.empno;
  end loop;
  --关闭游标
  close c1;
  commit;
end;

如有错误,欢迎指正!

猜你喜欢

转载自blog.csdn.net/qq_36260974/article/details/89053533
今日推荐