Oracle- 游标

  Oracle的游标比起SQLSERVER的游标,在写法上似乎更加灵活和方便些。

  在PL/SQL中处理显示游标所必需的四个步骤:

  1、声明游标;CURSOR cursor_name IS select_statement
  2、为查询打开游标;OPEN cursor_name
  3、取得结果放入PL/SQL变量中;
    FETCH cursor_name INTO list_of_variables;
    FETCH cursor_name INTO PL/SQL_record;
  4、关闭游标。CLOSE cursor_name
  注意:在声明游标时,select_statement不能包含INTO子句。当使用显示游标时,INTO子句是FETCH语句的一部分。

 

一、FOR循环游标 (常用的一种游标)

DECLARE
  --类型定义
  cursor cc is select sname,age,birthday from T_STUDENT;
  --定义一个游标变量
  ccrec cc%rowtype;
  begin
  --for循环
  for ccrec in cc loop
      
      dbms_output.put_line(ccrec.sname);
      dbms_output.put_line(ccrec.age);
      dbms_output.put_line(to_char(ccrec.birthday,'yyyy-MM-dd')  );
      dbms_output.put_line('-----------');
      
  end loop;       
end;

 

二、FETCH循环游标

--类型定义
declare 
  cursor cc is select sname,age,birthday from T_STUDENT;
  --定义一个游标变量
  ccrec cc%rowtype;
begin
  --打开游标
  open cc;
  --loop循环
  loop
  --提取一行数据到ccrec中 
  fetch cc into ccrec;
      exit when cc%notfound;
      dbms_output.put_line(ccrec.sname);
      dbms_output.put_line(ccrec.age);
      dbms_output.put_line(to_char(ccrec.birthday,'yyyy-MM-dd')  );
      dbms_output.put_line('-----------');
  end loop; 
  --关闭游标
close cc;  
end;


三、引用游标/动态游标

  --select语句是动态的
declare
  --定义一个类型(ref cursor)弱类型    
  type cur is ref cursor;
  --强类型(返回的结果集有要求)
  type cur1 is ref cursor return emp%rowtype;
  --定义一个ref cursor类型的变量   
  cura  cur;
  c1rec emp%rowtype;
  c2rec dept%rowtype;
begin
  DBMS_output.put_line('输出员工');
  open cura for
    select * from emp;
  loop
    fetch cura
      into c1rec;
    exit when cura%notfound;
    DBMS_output.put_line(c1rec.ename);
  end loop;
  DBMS_output.put_line('输出部门');
  open cura for
    select * from dept;
  loop
    fetch cura
      into c2rec;
    exit when cura%notfound;
    DBMS_output.put_line(c2rec.dname);
  end loop;
  close cura;
end;

 

posted @ 2015-01-08 13:30  春天又来了  阅读(161)  评论(0编辑  收藏  举报