Oracle之游標 使用(續)

2021-10-04 11:55:18 字數 2243 閱讀 6563

上節回顧:

1、游標

隱式游標:

select… into… from… where

dml命令

屬性:sql%isopen–假的 關閉的

sql%found

sql%notfound

sql%rowcount—受影響行數

顯式游標:

select… from… where 可以返回多行記錄

宣告游標、開啟游標、提取資料、關閉游標

不帶引數 帶引數

%isopen %found 、%notfound相當於@@fetch_status

%rowcount :已經從游標中提取的記錄的條數

——fetch 游標名 into

記錄變數名 表名%rowtype

記錄變數名 游標名%rowtype

本講內容:

1、直接使用for迴圈:

eg:

begin

for vsc in (select sno,sname from student) loop--或者 into游標名

dbms_output.put_line('sno:'||vsc.sno||',sname:'||vsc.sname);

end loop;

end;

輸出:

sno:2017005,sname:向華

sno:2017006,sname:肖戰

sno:2017001,sname:楊冪

sno:2017002,sname:李四

sno:2017003,sname:郭雅琦

sno:2017004,sname:王五

sno:2017007,sname:王一博

sno:2017008,sname:迪麗熱巴

2、使用游標來更新或刪除資料使用游標來更新資料時要加上 for update

當前行:通過where current of 游標名 來標識游標當前提取的資料行

eg:

declare

cursor cursc is select sno,cno,grade from sc for update;

vcno char:='1';

begin

for vsc in cursc loop

if vsc.cno=vcno then

dbms_output.put_line('sno:'||vsc.sno||',grade:'||vsc.grade);

update sc set grade =grade-10 where current of cursc;

end if;

end loop;

end;

輸出:

3、游標變數:

基於refcursor 型別所定義的變數:

declare

type refcursor is ref cursor;--定義refcursor型別

vcursor refcursor;--定義了乙個游標變數

vsname student.sname%type;

vsno student.sno%type;

begin

open vcursor for select sno,sname from student where s***='男';

loop

fetch vcursor into vsno,vsname;

exit when vcursor%notfound;

dbms_output.put_line('sno:'||vsno||',sname:'||vsname);

end loop;

close vcursor;

end;

輸出:

案例擴充套件:

入門oracle之游標

在寫oracle資料庫函式的時候,往往會返回乙個結果集,我們通過游標來實現這個操作,它的語法是 cursor 游標名 引數名 資料型別 引數名 資料型別 is select 語句 ex cusor a1 is select name from 表名 定義乙個a1的游標返回乙個表的所有name值。使用...

oracle存過之游標

游標的最簡單結構是 declare 定義乙個游標 cursor vrows is select from area where parent area 340000 游標的單列 vrow area rowtype begin 開啟游標 open vrows 迴圈 loop 注入,相當於for迴圈 f...

Oracle之游標使用以及優缺點

游標 cursor 能夠根據查詢條件從資料表中提取一組記錄,將其作為乙個臨時表置於資料緩衝區中,利用指標逐行對記錄資料進行操作。如下是查詢oracle scott下的emp表中empno為7788的姓名和工資。declare cursor cur emp p empno number is sele...