Oracle 游标

游标

游标的概念

游标是数据中处理查询语句,允许用户一次提取一行处理

逐行处理查询结果,以编程的方式访问数据

游标的关键词: cursor 

游标的类型

  • 隐式游标

  • 显式游标

  • 引用游标 Ref

游标的属性

  • %found 游标中是否含有数据

  • %notfound 游标中是否没有数据

  • %rowcount 影响行数

  • %isopen 游标的状态,是否打开,隐式游标始终为false

显示游标的使用步骤

  1. 声明游标: cursor 游标名称(参数列表) is select语句 

  2. 打开游标: open cur_emp(参数值); 

  3. 从游标中提取数据: fetch 游标名称 into 变量名称; 

  4. 关闭游标: close 游标名称; 

set serveroutput on;
declare
  cursor cur_emp(dno number) is select * from emp where deptno = dno;
  v_emp emp%rowtype; -- 如果只查询部分列,只需要自定义record类型
begin
  open cur_emp(&编号);
  loop
    fetch cur_emp into v_emp;
    exit when cur_emp%notfound;
    dbms_output.put_line(v_emp.empno || v_emp.ename);
  end loop;
  close cur_emp;
end;
/

循环游标

检化游标的遍历操作

declare
  cursor cur_emp is select * from emp;
begin
  for v_emp in cur_emp
  loop
      dbms_output.put_line(v_emp.ename);
  end loop;
end;
/

游标中更新和删除行

数据库中锁的概念:处理共享资源的并发访问问题

 select * from emp for update; 

引用游标

可以从多个select中来查询,类似与动态sql

弱类型游标的使用步骤

  1. 定义游标类型: type 类型名称 is ref cursor; 

  2. 声明游标: 游标名称 类型名称; 

  3. 打开游标: open 游标名称 for selec语句 

只有声明和打开部分与显式游标不一致,其他都一致

set serveroutput on;
​
declare
  type refType is ref cursor; -- 定义游标类型
  cur_emp refType; -- 定义游标
  v_emp emp%rowtype; -- 定义变量
begin
  open cur_emp for select * from emp; -- 打开游标
  loop
    fetch cur_emp into v_emp; -- 从游标中获取数据
    exit when cur_emp%notfound; -- 判断游标中是否还有数据
    dbms_output.put_line(v_emp.empno);
  end loop;
  close cur_emp; -- 关闭游标
end;
/

 

 

 

原文地址:https://www.cnblogs.com/sunhouzi/p/12435086.html