cursor
一、分類:
靜態游標
顯式游標(需要明確定義)
隱式游標(所有dml語句都為隱式游標,for循環也是隱式游標)
ref游標 (盡量不用ref游標,ref游標可在程序間傳遞數據集)
強類型ref游標(定義中有返回值)
弱類型ref游標(定義中無返回值)
二、游標的幾個狀態值:(%前接游標類型的變量)
%found
%notfound
%isopen
%rowcount:當前游標遍歷到的行值
三、粗暴的定義:用於遍歷查詢結果集,從而依次對結果集中的行做出相關操作;
四、各種游標簡單實例
--顯式游標----------------------
--loop循環
declare
cursor test_cursor is select * from dept;
test_ dept%rowtype;--也可寫為test_ test_cursor%rowtype;【此時test_cursor被看做一個結果集?】
begin
if test_cursor%isopen
then close test_cursor;
end if;
open test_cursor;
loop
fetch test_cursor into test_;
exit when test_cursor%notfound;
dbms_output.put_line(test_.deptno);
end loop;
dbms_output.put_line(test_cursor%rowcount);
close test_cursor;
end;
--隱式游標----------------------
--for循環
declare
cursor test_cursor is select * from dept;
--test_ test_cursor%rowtype;--這一段可忽略,游標變量在for循環中可直接使用,可不需要定義
begin
for test_ in test_cursor
loop
dbms_output.put_line(test_.loc);
end loop;
end;
/*
注:
for游標可不定義游標類型變量
for後接的就是游標類型變量
*/
--DML(update,insert,delete)
begin
update test_trans01 set b=111 where a='a';
if sql%rowcount<>0 then
dbms_output.put_line(sql%rowcount||'行被更新!');
end if;
end;
--強類型ref游標----------------------
declare
type test_cursor is ref cursor return test_trans01%rowtype;
test_ test_cursor;
test__ test_%rowtype;
begin
open test_ for select * from test_trans01;
loop
fetch test_ into test__;
exit when test_%notfound;
dbms_output.put_line(test__.a);
end loop;
close test_;
end;
--弱類型ref游標----------------------
declare
type test_cursor is ref cursor;
test_ test_cursor;
--test__ test_%rowtype;【這樣應用會報錯】
test__ dept%rowtype;
begin
open test_ for select * from dept;
loop
fetch test_ into test__;
exit when test_%notfound;
dbms_output.put_line(test__.dname);
end loop;
close test_;
end;
--應用實例----------------------
--for update/delete【用於修改或刪除表中數據】
declare
cursor test_cursor is select * from test_trans01 for update;--
begin
for test_ in test_cursor
loop
dbms_output.put_line(test_.a);
if test_.a='a' then
update test_trans01 set b=1111 where current of test_cursor;
dbms_output.put_line(test_.a||'被更新!');
else null;
end if;
end loop;
end;
--帶參數的顯示游標
--暫時未發現可用之處,或許可用在復雜的語句塊中,接收條件判定生成的參數,但講參數直接寫在where後是一樣的效果。。?
declare
cursor test_cursor(dd number :=2) is select * from test_trans01 where b>dd;--參數變量不能限定范圍
test_ test_cursor%rowtype;
begin
open test_cursor;
loop
fetch test_cursor into test_;
exit when test_cursor%notfound;
dbms_output.put_line(test_.b);
end loop;
close test_cursor;
end;