Oracle数据库—游标(cursor)实例

游标

游标是数据库的一个数据缓冲区,存放SQL语句执行结果。

用于遍历结果集和定位结果集的一条记录。

游标隐性属性

隐性游标属性 返回值类型 意义
%found 布尔型 从游标的结果集中获取记录时,找到了记录,为true
%notfound 布尔型 从游标的结果集中获取记录时,结果集中没有记录,为true
%rowcount 整型 代表DML语句成功执行的数据行数
%isopen 布尔型 DML执行过程中为真,结束后为假

声明游标

cursor 游标名称 is select语句

使用游标

for循环使用游标

例:输出emp表中的1004部门的员工 declare

  --声明游标,emp_corsor里面存储了select语句的多行记录

  cursor emp_corsor is select ename,ejob,esalary,ecomn from emp where did='1004';

  --声明变量c_row使用rowtype类型,存储一条记录

  c_row emp_corsor%rowtype;

begin

  --遍历游标emp_corsor,把获取的每一条记录存储到c_row中

  for c_row in emp_corsor loop

    dbms_output.put_line(c_row.ename||'-'||c_row.ejob||'-'||c_row.esalary||'-'||c_row.ecomn);

  end loop;

end;

fetch使用游标

----------必须先要打开游标,用完后需要关闭

打开游标

open 游标名称;

关闭游标

close 游标名称;
declare

    --声明游标,emp_corsor里面存储了select语句的多行记录

  cursor c_emp is select esalary,ecomn from emp where did='1004';

  --声明变量c_row使用rowtype类型,存储一条记录  

  c_row c_emp%rowtype;

begin

  --打开游标

  open c_emp;

  --循环输出数据

  loop

    --将c_emp游标中的记录,提取一行记录到c_row

    fetch c_emp into c_row;

    --%notfound 找不到时候返回ture,找到值返回false

    --结合exit使用,判读是否提取到值,没取到值就退出

    --取到值c_job%notfound 是false

    --取不到值c_job%notfound 是true

    exit when c_emp%notfound;

    dbms_output.put_line(c_row.esalary||'-'||c_row.ecomn);

  end loop;

  --关闭游标

  close c_emp;

end;

猜你喜欢

转载自yq.aliyun.com/articles/675845