Oracle游標使用

2021-08-21 04:56:28 字數 2468 閱讀 5567

一,什麼是游標

遍歷查詢結果集的一種機制。

二,為什麼避免使用游標

盡量避免使用游標, 因為游標的效率較差;

如果使用了游標,就要盡量避免在游標迴圈中再進行表連線的操作。

三,使用游標的步驟(靜態游標)

1,宣告一些變數,用來儲存游標遍歷過程的臨時資料

2,宣告游標,並且指定查詢

3,開啟游標

4,從游標中獲取一行或多行記錄

5,關閉游標

四,游標的屬性

1,%isopen:是否開啟游標

2,%rowcount:游標的行數

3,%found:是否還有資料

4,%notfound:是否沒有資料

五,游標的分類(下面的分類不是並列關係)

1,靜態游標:使用游標前就已經定義好,並且不能更改

2,動態游標:游標在宣告時沒有定義好,在開啟時可以做更改

3,顯示游標:使用游標前要宣告、開啟游標,使用完成需要關閉

4,隱示游標:事先沒有宣告開啟游標,直接使用,也不需要關閉

5,強型別游標:宣告游標時帶return關鍵字,游標只能與特定的查詢匹配

6,弱型別游標:宣告游標時不帶return關鍵字,游標可以與任意查詢匹配

六,游標的具體使用栗子:

1,先建立表結構和插入資料

create table students(

id number,

name varchar2(10),

age number

);insert into students values(1,'李白',18);

insert into students values(2,'妲己',16);

insert into students values(3,'趙信',20);

commit;

2,隱式游標

declare

begin

for student in(select * from students) loop

dbms_output.put_line('編號:'||student.id||',姓名:'||student.name||',年齡'||student.age);

end loop;

end;

3,顯式游標

declare

cursor mycur is select * from students;

student students%rowtype;

begin

open mycur;

loop

fetch mycur into student;

exit when mycur%notfound;

dbms_output.put_line('編號:'||student.id||',姓名:'||student.name||',年齡'||student.age);

end loop;

close mycur;

end;

4,動態游標之強型別游標

--列印年齡小於18的學生

create or replace procedure printstudents(in_age in varchar2)

as --自定義型別

type student_type is record(

id number,

name varchar2(10)

);type students_type is ref cursor return student_type;--定義游標型別

students students_type;--宣告游標變數

student student_type;--宣告變數

begin

open students for select id,name from students where agefetch students into student;--游標指標指向下一行

while students%found loop--遍歷游標

dbms_output.put_line('編號:'||student.id||',姓名:'||student.name);

fetch students into student;--游標指標指向下一行

end loop;

close students;--關閉游標

end;

declare

p_v number;

begin

p_v:=&請輸入年齡;

printstudents(p_v);

end;

oracle 游標使用

create or replace function errortyperead return varchar2 is result varchar2 3000 type cursor type is ref cursor tempname varchar2 100 cursor testcur i...

oracle游標使用

在進行pl sql程式設計時,我們都會使用游標,游標有兩種,一種是顯式游標,使用類似如下方式 open 游標 loop fetch into exit when notfound end loop close 游標 另一種是隱式游標,使用類似如下 for 游標變數 in 游標 loop 賦值變數 游...

oracle游標使用

游標 用來查詢資料庫,獲取記錄集合 結果集 的指標,可以讓開發者一次訪問一行結果集,在每條結果集上作操作。分類 靜態游標 分為顯式游標和隱式游標。ref游標 是一種引用型別,類似於指標。顯式游標 cursor 游標名 引數 返回值型別 is select 語句 生命週期 1.開啟游標 open 解析...