Oracle中的游標

2021-08-31 23:41:03 字數 3588 閱讀 1227

游標:用來處理使用select語句從資料庫中檢索到的多行記錄的工具。

1、游標的分類

1、顯示游標:返回多條記錄時,使用顯示游標逐行讀取

2、隱式游標:pl/sql自動為dml語句建立隱式游標,包含一條返回記錄

2、顯示游標

1、顯示游標的使用步驟:

--宣告游標

cursor cursor_name [(parameter [,parameter]...)]

[return return_type] is select_statement;

--開啟游標

open cursor_name [(parameters)];

--提取游標

fetch cursor_name into variables;

--關閉游標

close cursor_name;

2、顯示游標的屬性:

屬性名稱 

說  明 

%found 

用於檢驗游標是否成功,通常在fetch語句前使用,當游標按照條件查詢出一條記錄時,返回true 

%isopen 

判斷游標是否處於開啟狀態,檢視開啟乙個已經開啟或者已經關閉的游標,將會出現錯誤 

%notfound 

與%found的作用相反,當按照條件無法查詢到記錄時,返回true 

%rowcount 

迴圈執行游標讀取資料時,返回檢索出的記錄資料的行數 

3-1、顯示游標--不帶引數

declare

cursor emp_cursor is--建立游標

select ename,sal

from emp

where empno=7788;

--宣告兩個變數

v_ename emp.ename%type;

v_sal emp.sal%type;

begin

open emp_cursor;--開啟游標

loop

fetch emp_cursor into v_ename,v_sal;--讀取游標

----判斷游標是否為空

exit when emp_cursor%notfound;

dbms_output.put_line('v_ename:'||v_ename || ';v_sal='||v_sal);

end loop;

close emp_cursor;--關閉游標

end;

3-2、顯示游標--帶引數

declare

cursor emp_cursor(no number) is--建立游標

select ename

from emp

where empno=no;

--宣告兩個變數

v_ename emp.ename%type;

begin

if not emp_cursor%isopen then

open emp_cursor(7788);

end if;

loop

fetch emp_cursor into v_ename;--讀取游標

----判斷游標是否為空

exit when emp_cursor%notfound;

dbms_output.put_line('v_ename:'||v_ename);

end loop;

close emp_cursor;--關閉游標

end;

3-3、顯示游標--迴圈游標

declare

cursor emp_cursor(no number) is--建立游標

select ename,sal

from emp

where empno=no;

begin

for emp_record in emp_cursor(7788)

loop

dbms_output.put_line('v_ename:'|| emp_record.ename);

end loop;

end;

4、使用顯示游標刪除或更新

語法

cursor cursor_name is

select_statement for update [of columns];

注意:for update [of columns]為更新查詢,鎖定選擇的行

(1)單錶查詢時,可以省略of 子句。

(2)多表查詢時,鎖定的行**於,of子句後宣告的列所在的表中的行,省略of子句,則都鎖。

of後的列在哪個表,就鎖的是哪個表的行

例子:假設emp表中有sal欄位;dept表中有dname欄位。

for update sal            則鎖定emp表中的行;

for update dname       則鎖定dept表中的行。

示例

declare

cursor emp_cursor is--建立游標

select ename,sal

from emp e inner join dept d

on e.deptno=d.deptno

for update of e.sal;

--宣告兩個變數

v_ename emp.ename%type;

v_sal emp.sal%type;

begin

if not emp_cursor%isopen then

open emp_cursor;--開啟游標

end if;

loop

fetch emp_cursor into v_ename,v_sal;--讀取游標

----判斷游標是否為空

exit when emp_cursor%notfound;

update emp set sal=v_sal+200 where current of emp_cursor;

--update emp set ename='bdqn' where current of emp_cursor;

end loop;

close emp_cursor;--關閉游標

end;

Oracle中的游標

cursor found最近一次讀取是否成功 notfound isopen游標開啟時返回true rowcount返回已從游標讀取的記錄數 輸出年齡大於等於18的使用者的id跟name declare v id t.id type v name t.name type cursor c user ...

Oracle中的游標

oracle 中的游標 游標 cursor 在pl sql 中可以增強 sql語句的功能,游標是用來查詢資料 獲取結果集中記錄的指標。它可以讓開發者在結果集中訪問結果集中的一行。游標以程式設計的方式訪問資料,從而完成在結果集的每個記錄上的操作。也就是說,游標就是結果集中的記錄指標,該指標指向查詢結果...

oracle 中的游標

oracle 中的游標 通俗易懂的sql 直接上!簡單的游標使用滴呀 使用for obj in objs loop end loop declare cursor c job isselect name,course,greade from stu c row c job rowtype begin...