原理:plsql塊執行查詢和資料操縱dml時,oracle會為其配置設定上下文區(Contextarea),而遊标是指向上下文區的指針,是以操縱遊标,就是在操縱指針,應該快不少哈。
目标:
1)使用顯示遊标及遊标屬性
2)使用參數遊标
3)使用顯示遊标更新或删除資料
4)使用遊标for循環
5)使用遊标變量
6)使用fetch * bulk collect into 語句和cursor表達式處理多行多列
個人了解一定要靈活使用,遊标與複合表,是操作單條多列還是多列多行,單列多行,然後在去選擇對應的表或者遊标,開始不熟的時候使用一定要先想,用這個處理行不行,這樣能幫助你回憶以前記憶的遊标的知識,一一排除及找到肯定的以後,這樣熟了以後就快了
個人了解隐含式遊标隻有那種處理select into和dml的語句是,即單行的資料 這裡還是有疑問
顯示遊标呢處理多行單列或者多列的資料。
【顯示遊标】
使用顯示遊标記住幾步:定義 、打開、周遊、關閉
declare cursor cursor_name is select_statement;
open cursor_name;
fetch cursor_name into variable1,variable2...
fetch cursor_name bulk collect into collect1,collect2...
close cursor_name;
【遊标屬性】
顯示遊标屬性用于傳回顯示遊标的執行資訊,包括%ISOPEN,%FOUND,%NOTFOUND,%ROWCOUNT,一定要注意與PLSQL異常區分開如NOT_DATA_FOUND ,TOO_MANY_ROWS等
eg:fetch * into 一次隻能處理一條語句,為了處理多條需要使用循環
open emp_cursor;
loop
fetch emp_cursor into v_ename,v_sal ;
exit when emp_cursor%NOTFOUND;
dbms_output.put_line(v_ename||v_sal);
end loop;
close emp_cursor;
end;
fetch * bulk collect into提取全部資料
fetch emp_cursor bulk collect into ename_table;
for i in 1..ename_table.count loop
dbms_output.put_line(ename_table(i));
end;個人了解這種方式隻在處理當列多行方面比較在行
還有一個方法是 fetch * bulk collect into limit rows限制行,就是可以輸入多少行。
用遊标定義記錄變量
cursor emp_cursor is select ename,sal from emp;
emp_record emp_cursor%ROWTYPE:
fetch emp_cursor into emp_record;
dbms_output.put_line(emp_record.sal);
【參數遊标】
參數遊标顧名思義肯定是遊标裡邊需要一個輸入參數,這個參數隻能指定資料類型,沒有長度,在遊标子查詢的where字句中引用該參數,否則失去了遊标的意義。
declare
cursor emp_cursor(no number) is
select ename,sal from emp where deptno=no;
就是每次輸入不同的no值就會得到不同的結果,
【遊标更新删除資料此項比較複雜,容易引起問題,後續補充不建議使用】
【遊标的for循環】
遊标的for循環會隐式的打開遊标,提取資料并關閉遊标,每循環提取一次資料
for record_name in cursor_name loop
statement1;
statement2;
..
CURSOR emp_cursor is select ename,sal from emp;
begin
for emp_record in emp_cursor loop
dbms_output.put_line(emp_cursor%ROWCOUNT||emp_record.ename);
簡寫的
for emp_record in (select ename,sal from emp) loop
dbms_output.put_line(emp_record.ename);
顯示遊标與遊标變量的差別,顯示遊标定義的時候指明select 而遊标變量定義是不需要select,可以在打開的時候指定select 也就是open emp_cursor for select_statement;
【遊标變量】
為了使用遊标變量,必須使用參照類型ref cursor
type ref_type_name is ref cursor [return return_type]
cursor_variable ref_type_name;
cursor_variable就是遊标變量名
打開遊标
open cursor_variable for select_statement;
提取資料
fetch cursor_variable into variable1,variable2..;
fetch cursor_variable bulk collect into collect1,collect2..
關閉遊标
close cursor_variable
eg:定義參照類型的遊标變量
type emp_cursor_type ref cursor;
emp_cursor emp_cursor_type;
emp_record emp_cursor%ROWTYPE;
open emp_cursor for select * from emp;
exit when emp_cursor%NOTFOUND ;
end ;
eg:定義參照類型的時候如果指定了return字句,那麼傳回的必須與定義的類型比對,
type emp_record_type is record(
name varchar2(10),salary number(6,2)
);
type emp_cursor_type is ref cursor return emp_cursor_type; 帶傳回的參照變量
emp_record emp_record_type;
open emp_cursor for select ename,sal from emp where deptno=20;
dbms_output.put_lin(emp_cursor%ROWTYPE||emp_record.name);
本文轉自 aklaus 51CTO部落格,原文連結:http://blog.51cto.com/aklaus/1954204