oracle學習筆記(五)游標

2021-08-04 13:31:03 字數 1583 閱讀 6608

游標在資料庫操作中有著十分重要的作用,它簡單地說就相當於指標,針對表中檢索出來的結果進行操作,游標分為顯示游標和隱式游標。

顯示游標是使用者可以自己宣告和操作的,通常用於操作查詢結果集。通過他來處理資料主要分為四步驟,首先是宣告游標,其次是開啟游標,然後讀取游標,最後關閉游標。

1.宣告游標必須指定名稱和使用的select語句,語法為cursor cursor_name(引數) [return type] is select ***;宣告的時候可以新增輸入引數和返回型別。

2.開啟游標 open cur_name(引數)

3.讀取游標 fetch cur_name into (引數),剛剛開啟游標的時候,指標指向結果集的第一行,使用fetchinto語句之後,游標中的指標自動指向下一行資料。

4.關閉游標,close cur_name;以便釋放系統資源。

下面的例子是根據scott使用者下的emp表進行操作,對不同職位的員工進行不同漲幅的工資增長。

declare

rate_man constant number := 0.15;--工資漲幅

rate_salman constant number := 0.12;

rate_clerk constant number := 0.1;

v_job emp.job%type;

v_name emp.ename%type;

v_no emp.empno%type;

cursor c_emp is

select emp.job, emp.empno, emp.ename from emp for update;

begin

open c_emp;

loop

fetch c_emp--讀取游標

into v_job, v_no,v_name;

exit when c_emp%notfound;

if v_job = 'salesman' then

update emp

set emp.sal = emp.sal * (1 + rate_salman)

where current of c_emp;

elsif v_job = 'clerk' then

update emp

set emp.sal = emp.sal * (1 + rate_clerk)

where current of c_emp;

elsif v_job = 'manager' then

update emp

set emp.sal = emp.sal * (1 + rate_man)

where current of c_emp;

end if;

dbms_output.put_line('已經為員工' || v_no || ':' || v_name || '成功加薪');

end loop;

close c_emp;

exception

when no_data_found then

dbms_output.put_line('沒有找到員工資料');

end;

Oracle游標學習筆記

游標按以下操作進行 parse 解析 bind 繫結 open 開啟 execute 執行 fetch 回取 close 關閉 1.寫自己第乙個游標pl sql declare cursor c s is select from user tables begin open c s 開啟游標 clo...

oracle游標筆記

游標 cursor 也叫游標,在關聯式資料庫中經常使用,在pl sql程式中可以用cursor與select一起對錶或者檢視中的資料進行查詢並逐行讀取。oracle游標分為顯示游標和隱式游標。顯示游標 explicit cursor 在pl sql程式中定義的 用於查詢的游標稱作顯示游標。隱式游標 ...

oracle學習筆記五

top n 分析的語法 select column list rownum from select column list from table order by top n column where rownum n select empno,ename,job from select rownu...