遊標按以下操作進行
parse 解析
bind 綁定
open 開啟
execute 執行
fetch 回取
close 關閉
1.寫自己第一個遊標PL/SQL
declare
cursor c_s is select * from user_tables;
begin
open c_s; --開啟遊標
close c_s;--關閉遊標
end;
遊標的4個屬性 %found,%notfound,%rowcount,%isopen
1.%found 遊標有記錄則返回true否則false
declare
cursor c_s is select * from user_tables;
cc c_s%rowtype;
begin
open c_s; --開啟遊標
fetch c_s into cc;
while c_s%found loop
fetch c_s into cc;
end loop;
close c_s;--關閉遊標
end;
2.%notfound 遊標沒記錄則返回true否則false(個人感覺有點多餘)
declare
cursor c_s is select * from user_tables;
cc c_s%rowtype;//遊標變數
begin
open c_s; --開啟遊標
fetch c_s into cc;
while c_s%found loop
exit when c_s%notfound;
end loop;
close c_s;--關閉遊標
end;
3.%rowcount 返回遊標取回的記錄數目
declare
cursor c_s is select * from user_tables;
cc c_s%rowtype;
begin
open c_s; --開啟遊標
fetch c_s into cc;
while c_s%found loop
dbms_output.put_line(c_s%rowcount);
end loop;
close c_s;--關閉遊標
end;
4.%isopen 如果遊標開啟就返回true 否則false
declare
cursor c_s is select * from user_tables;
begin
if c_s%isopen then
dbms_output.put_line('cursor is open');
else
open c_s; --開啟遊標
end if;
close c_s;--關閉遊標
end;
遊標參數
declare
cursor c_s(cs_id number) is select * from admin id=cs_id;
begin
open c_s(10); --開啟帶參數的遊標
close c_s;--關閉遊標
end;
遊標中的for update
declare
cursor c_s is select id from admin
for update of id //查詢時鎖定 id列
begin
open c_s;
commit;//提交釋放鎖 或者可以用 rollback
close c_s;
end;
遊標中的where cursor of
UPDATE table_name SET set_clause WHERE CURSOR OF cursor_name; //更新遊標所指向的那條記錄
DELETE FROM table_name WHERE CURSOR OF cursor_name; //刪除遊標所指向的那條記錄
遊標中的ref cursor類型
TYPE c_s IS REF CURSOR RETRUN table%rowtype; //這種形式為強型別 在聲明的時候就定了為行類型
TYPE c_s IS REF CURSOR;//弱類型 不與記錄的資料類型關聯
例子:
declare
TYPE c_s IS REF CURSOR RETRUN table%rowtype;
TYPE c_s2 IS REF CURSOR;
var_cs c_s;//聲明為遊標變數的類型
begin
OPEN c_s FOR select * from admin;
CLOSE c_s;
end;