遊標(cursor)
可以使用遊標獲取查詢返回的行。在通過查詢將行檢索到遊標中後,可以一次從遊標中取出一行。
1.步驟
使用遊標遵循下面5個步驟:
步驟1:聲明用於保存列值的變量
注意:這些變量必須與列的類型兼容。
例如:
declare
v_id test.id%TYPE;
v_type test.type%TYPE;
步驟2:聲明遊標
由遊標名和希望執行的查詢組成。
例如:
cursor v_test_cursor is
select id,type
from test;
步驟3:打開遊標
open v_test_cursor;
步驟4:從遊標中取得行
使用fetch:將列的值讀取到在第1步聲明的變量中。
例如:
將列的值讀取到在第1步聲明創建的v_id和v_type中。
fetch v_test_cursor
into v_id,v_type
步驟5:關閉遊標
close v_test_cursor;
完整示例:
declare
v_id test.id%TYPE;
v_type test.type%TYPE;
cursor v_test_cursor is
select id,type
from test;
begin
open v_test_cursor;
loop
fetch v_test_cursor
into v_id,v_type;
exit when v_test_cursor%NOTFOUND;
dbms_output.put_line(v_id || v_type);
end loop;
close v_test_cursor;
end;
結果:
101
201
2.遊標與for循環使用
for循環時,可以不顯式的打開和關閉遊標。for循環會自動執行這些操作。
例如:
declare
cursor v_test_cursor is
select id,type from test;
begin
for v_test in v_test_cursor loop
dbms_output.put_line(v_test.id || v_test.type);
end loop;
end;
結果:
101
201
3.OPEN-FOR語句
可以將遊標分配給不同的查詢,因此可以靈活的處理遊標
declare
type t_test_cursor_1 is ref cursor
return test%ROWTYPE; --聲明的ref cursor(指向遊標的指針)類型名爲
t_test_cursor t_test_cursor_1;
v_test test%ROWTYPE; --返回test表中各行的一列,v_test用來存儲test表的各列。
begin
open t_test_cursor for --test表中的所有數據加載到t_test_cursor遊標中
select * --這裏也是要寫成*號,如果是字段,就報錯!不明白爲麼????
from test;
loop
fetch t_test_cursor into v_test;
exit when t_test_cursor%NOTFOUND; --確定何時結束,當不能讀出行時,爲true,是一個布爾類型
dbms_output.put_line(v_test.id || v_test.type);
end loop;
close t_test_cursor;
end;
結果:
101
201
4.無約束遊標
具有具體的返回類型,爲約束遊標。
約束遊標返回的類型必須與遊標運行時返回的類型相匹配。
無約束遊標沒有返回類型。
declare
type t_cursor is ref cursor;
v_cursor t_cursor;
v_test test%ROWTYPE;
v_order order%ROWTYPE;
begin
open v_cursor for
select * from test;
loop
fetch v_cursor into v_test;
exit when v_cursor%NOTFOUND;
dbms_output.put_line(v_test.id || v_test.type);
end loop;
open v_cursor for
select * from order;
loop
fetch v_cursor into v_order;
exit when v_cursor%NOTFOUND;
dbms_output.put_line(v_order.id || ' ' ||v_order.status);
end loop;
close v_cursor;
end;
結果:
101
201
1 new