Oracle之游标

/*
   游标 是用于接收查询的记录结果集  ResultSet 提取记录 .next() 
        使用步骤
        声明游标  cursor  游标名  is select 语句
        打开游标  open    游标名
        提取动作  fetch  游标名  into 记录类型变量
                  游标%found  提取到记录
                  游标%notfound 没有提取到
        关闭游标  close 游标名
*/

--使用游标提取emp表中所有记录
declare
    cursor emp_cursor is select * from emp;  --声明游标
    emp_row emp%rowtype; --记录类型用于接收游标提取
begin
    open emp_cursor; --打开游标
   
    if emp_cursor%found then
       dbms_output.put_line('found');
    elsif  emp_cursor%notfound  then
       dbms_output.put_line('notound');
    elsif  emp_cursor%found is null  then
       dbms_output.put_line('null');
    end if;
    --先提取游标 再进行判断
    fetch emp_cursor into emp_row;
    while emp_cursor%found loop
      dbms_output.put_line('empno===='||emp_row.empno||'ename=='||emp_row.ename);
      fetch emp_cursor into emp_row;
    end loop;
    close emp_cursor;--关闭游标
end;
--使用loop 循环提取游标
declare
    cursor emp_cursor is select * from emp;  --声明游标
    emp_row emp%rowtype; --记录类型用于接收游标提取
begin
    open emp_cursor; --打开游标
  
     loop
       fetch emp_cursor into emp_row;  --保证先提取再判断
       exit when emp_cursor%notfound;
       dbms_output.put_line('empno===='||emp_row.empno||'ename=='||emp_row.ename);
      
    end loop;
    close emp_cursor;--关闭游标
end;
--使用带参数的游标 提取某个部门的员工信息
declare
    cursor emp_cursor(dno number) is select * from emp where deptno=dno;  --声明游标
    emp_row emp%rowtype; --记录类型用于接收游标提取
begin
    open emp_cursor(20); --打开游标
  
     loop
       fetch emp_cursor into emp_row;  --保证先提取再判断
       exit when emp_cursor%notfound;
       dbms_output.put_line('empno===='||emp_row.empno||'ename=='||emp_row.ename);
      
    end loop;
    close emp_cursor;--关闭游标
end;

posted on 2017-12-20 09:18  一只小小小兔兔  阅读(283)  评论(0编辑  收藏  举报

导航