簡單的游標

2021-07-25 03:55:21 字數 2297 閱讀 9979

為什麼要用到游標呢?因為我們都知道,在pl/sql 中,每次只能返回單行的資料,當返回多行時,資料庫會報錯,所以,游標就誕生了。那游標又是如何做得到呢?原來,游標類似於指標一樣,他可以逐行的讀取sql,然後輸出。

我們可以通過以下步驟,定義和使用游標:

1 申明(declare)乙個游標

2 開啟(open)游標

3 讀取(fetch)游標

4 關閉(close)游標

列 declare

cursor c_student_name is

select first_name,last_name from student

where rownum<5;

vr_student_name c_student_name%rowtype;

begin

open c_student_name;

loop

fetch c_student_name into vr_student_name;

exit when c_student_name%notfound;

dbms_output.put_line('student name:'||vr_student_name.first_name||''||vr_student_name.last_name);

end loop;

close c_student_name;

end;

那為什麼要用到loop呢?因為游標包含多個變數,所以要通過迴圈來賦值。為了簡化語法,處理游標的另一種方式被叫做for迴圈,使用時開啟,讀取和關閉被隱式處理,提高了效率。

declare

cursor c_student is

select student_id,last_name,first_name from student

where student_id<100;

begin

for r_student in c_studnet

loop

insert into class

values( r_student.last_name);

end loop;

end;

以上為顯示游標,其實還有一種叫做隱式游標的。

1 任何給定的塊中,若無顯示游標,就會發出乙個隱式游標。

2 游標會自動的與每乙個dml語言相關聯。

3 insert語句需要有乙個地方來接受插入的資料,隱式游標滿足了這一要求。

游標還可以帶引數,但是要注意以下幾點:

1.游標引數可以被賦予預設值

2.引數只能是模式 in

當游標已被申明為接受引數的游標後,呼叫他時,就必須包括此引數的值。

例: declare

cursor c_zip(p_state in zipcode.stste%type) is

select zip,city,state from zipcode

where state= p_state

begin

for r_zip in c_zip(『nanjing』)

loop

exit when r_zip%notfound;

dbms_output.put_line(r_zip.city||』 『||r_zip.state);

end loop;

end;

還有一種游標叫做for update 游標

使用 for update 子句的目的是鎖住你要更新的行,使用commit或rollback語句釋放鎖。在要鎖定乙個表中的既包含指定列之一,又是活動集的成員的行時,可以用for update of 專案名 來完成。

例 declare

cursor c_student_zip is

select s.student_id,z.city from student s, zipcode z

where z.city=』nanjing』 and s.zip=z.zip

for update of phone;

begin

for r_student_zip in c_student_zip

loop

exit when c_student_zip%notfound;

update student

set phone=』021』 where student_id=r_student_zip.student_id;

end loop;

end;

所以,由這幾個塊中,我們可以看到,凡是有游標的,必須有for 和loop,來進行讀取。

簡單游標分析

set nocount on 建立測試環境 當 set nocount 為 on 時,不返回計數 declare tb table id int 定義臨時表 insert tb id 插入資料 select id 1 union all select id 2 union all select id...

oracle游標簡單demo

declare 定義變數 row info varchar2 200 定義游標 cursor cur dept is select from emp where deptno 10 定義乙個游標變數cur dept row cur dept rowtype,該型別為游標cur dept中的一行資料型...

sqlserver簡單游標使用

這個是乙個簡單的user表叫my user 以下 及注釋 注 為注釋 建立乙個游標 declare my cursor cursor for my cursor為游標的名稱,隨便起 select id,name from my user 這是游標my cursor的值,這裡隨便發揮看業務場景 開啟游...