ORACLE/PLSQL 游标的简单使用

来源:互联网 发布:张居正 高拱 知乎 编辑:程序博客网 时间:2024/04/29 01:28
游标的属性 %found,%notfound,%isopen,%rowcount。
    %found:若前面的fetch语句返回一行数据,则%found返回true,如果对未打开的游标使用则报ORA-             1001异常。
    %notfound,与%found行为相反。
    %isopen,判断游标是否打开。
    %rowcount:当前游标的指针位移量,到目前位置游标所检索的数据行的个数,若未打开就引用,返回ORA-1001。
1.方法一:
Declare
  Cursor my_cursor is select r.person_id,r.emp_number,r.emp_name from hr_user r where rownum between 1 and 10;
  My_rec my_cursor%rowtype;
Begin
  Open my_cursor; --如果这行错误可以注销
  loop
  Fetch my_cursor into My_rec ;
   DBMS_OUTPUT.PUT_LINE('员工号:' || My_rec.Person_Id ||  ',员工编号:' || My_rec.Emp_Number || ',员工姓名:' || My_rec.Emp_Name );
  Exit when my_cursor%notfound;
  End loop;
  Close my_cursor;
END;
2.方法二:
Declare
  Cursor my_cursor is select r.person_id,r.emp_number,r.emp_name from hr_user r where rownum between 1 and 10;
Begin
  For My_rec in My_cursor loop
    DBMS_OUTPUT.PUT_LINE('员工号:' || My_rec.Person_Id ||  ',员工编号:' || My_rec.Emp_Number || ',员工姓名:' || My_rec.Emp_Name );
  end loop;
END;
3.方法三:
Declare
  Cursor My_cursor is select r.person_id,r.emp_number,r.emp_name from hr_user r where rownum between 1 and 10;
  My_rec my_cursor%rowtype;
Begin
   Open my_cursor;
   Fetch My_cursor into My_rec;
   While (my_cursor%found) loop
    DBMS_OUTPUT.PUT_LINE('员工号:' || My_rec.Person_Id ||  ',员工编号:' || My_rec.Emp_Number || ',员工姓名:' || My_rec.Emp_Name );
   Fetch My_cursor into My_rec;
   End Loop;
END;
原创粉丝点击