Oracle PL/SQL基礎 遊標

來源:互聯網
上載者:User

Oracle的遊標分為顯式遊戲、隱式遊戲,顯式遊標是指使用者自己定義、操作的,用於處理查詢返回多行的SELECT查詢結果;隱式遊標是系統自動進行操作、用於處理DML語句和返回單行資料的SELECT查詢。

在本文,主要討論顯式遊標。

一、遊標的使用步驟

步驟分四步:定義遊標、開啟遊標、檢索遊標、關閉遊標。

1、定義遊標

遊標必須在PL/SQL塊的聲明部分定義。

CURSOR cursor_name IS select_statement ;

定義遊標時,並沒有產生seletct_statement(SELECT查詢)的資料,當開啟遊標後,才真正產生資料。

2、開啟遊標

OPEN cursor_name ;

只有開啟遊標後,才會從資料庫中查詢出資料,緩衝到記憶體配置的緩衝區裡。

3、檢索遊標

FETCH curso_name INTO variable_list ;

檢索遊標的前提是,必須開啟了遊標,只有開啟了遊標了,緩衝區才會有資料。
 
遊標檢索資料,只能下移,不能回退,如:檢索了第二條資料又想檢索第一條資料,則必須先關閉遊標後,再開啟遊標,才能檢索第一條資料。
 
4、關閉遊標
 
處理完遊標檢索出來的資料後,必須關閉遊標,才能釋放它所佔用的系統資源,如所佔用的內在緩衝區

CLOSE curso_name ;

rlwrap - 解決Linux下SQLPLUS退格、上翻鍵亂碼問題

SQLPLUS spool 到動態記錄檔名

Oracle SQLPLUS提示符設定

通過設定SQLPLUS ARRAYSIZE(行預取)加快SQL返回速度

二、遊標使用例子

declare
  -- declare cursor
  cursor c_dept is
  select * from dept t order by t.deptno;
  v_dept c_dept%rowtype;
begin
  --open cursor c_dept
  open c_dept;
 
  --檢索cursor c_dept
  loop
    fetch c_dept into v_dept;
    dbms_output.put_line
    ('deptno:'||v_dept.deptno||',dname:'||v_dept.dname||',loc:'||v_dept.loc);
    exit when c_dept%notfound;
  end loop;
 
  --close cursor
  close c_dept;
end;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.