oracle遊標的使用

--當select語句從數據庫中返回的記錄多餘一條時,就可以使用遊標(cursor)。遊標可以理解爲一次訪問一個的一組記錄。select語句將列提取到遊標中,然後根據遊標取得記錄。使用遊標時需要遵從以下的5個步驟:
(1)聲明一些變量,用於保存select語句返回列值
(2)聲明遊標,並制定select語句
(3)打開遊標
(4)從遊標獲取記錄

(5)關閉遊標

<span style="font-size:18px;">-- 遊標的使用
set serveroutput on;
declare
  --聲明變量
  sname varchar2( 20);
  --聲明遊標
  cursor student_cursor is select sn from s; 
  begin
      --打開遊標
      open student_cursor;
      --讓遊標指針往下移動
      fetch student_cursor into sname ;
      --判斷遊標指針是否指向某行記錄
      while student_cursor%found 
        --遍歷
        loop
          dbms_output.put_line ('學生姓名' ||sname );
          fetch student_cursor into sname;
        end loop;
     close student_cursor;
end;

--遊標的使用遊標,for循環是在pl/sql塊中使用遊標最簡單的方式,它簡化了對遊標的處理。
--當使用遊標for循環時,oracle會隱含的打開遊標,提取遊標數據並關閉遊標。
set serveroutput on;
declare
  --聲明遊標
  cursor student_cursor is select sn, dept from s;  
  begin
      --打開遊標
      --open student_cursor;
      --讓遊標指針往下移動
      for st in student_cursor     
        loop
          --fetch student_cursor into st;
          dbms_output.put_line ('學生姓名' ||st.sn ||'學生系別'||st.dept);
        end loop;
      close student_cursor;
  end;
</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章