Oracle PL SQL游標的學習

2021-04-13 22:52:27 字數 2524 閱讀 7389

一 游標是什麼

游標字面理解就是游動的游標。

用資料庫語言來描述:游標是對映在結果集中一行資料上的位置實體,有了游標,使用者就可以訪問結果集中的任意一行資料了,將游標放置到某行後,即可對該行資料進行操作,例如提取當前行的資料等。

二 游標的分類

顯式游標和隱式游標

顯式游標的使用需要4步:

1. 宣告游標

cursor mycur(vartype number) is

select emp_no,emp_zc from cus_emp_basic

where com_no = vartype;

2. 開啟游標

open mycur(000627)

注:000627是引數

3. 讀取資料

fetch mycur into varno, varprice;

4. 關閉游標

close mycur;

三 游標的屬性

oracle 游標有4個屬性:%isopen,%found,%notfound,%rowcount。

%isopen判斷游標是否被開啟,如果開啟%isopen等於true,否則等於false;

%found %notfound判斷游標所在的行是否有效,如果有效,則%foundd等於true,否則等於false;

%rowcount返回當前位置為止游標讀取的記錄行數。

四 示例

set serveroutput on;

declare

varno varchar2(20);

varprice varchar2(20);

cursor mycur(vartype number) is

select emp_no,emp_zc from cus_emp_basic

where com_no = vartype;

begin

if mycur%isopen = false then

open mycur(000627);

end if;

fetch mycur into varno,varprice;

while mycur%found

loop

dbms_output.put_line(varno||','||varprice);

if mycur%rowcount=2 then

exit;

end if;

fetch mycur into varno,varprice;

end loop;

close mycur;

end;

pl/sql記錄的結構和c語言中的結構體類似,是由一組資料項構成的邏輯單元。

pl/sql記錄並不儲存在資料庫中,它與變數一樣,儲存在記憶體空間中,在使用記錄時候,要首先定義記錄結構,然後宣告記錄變數。可以把pl/sql記錄看作是乙個使用者自定義的資料型別。

set serveroutput on;

declare

type person is record

(empno cus_emp_basic.emp_no%type,

empzc cus_emp_basic.emp_zc%type);

person1 person;

cursor mycur(vartype number)is

select emp_no,emp_zc from cus_emp_basic

where com_no=vartype;

begin

if mycur%isopen = false then

open mycur(000627);

end if;

loop

fetch mycur into person1;

exit when mycur%notfound;

end loop;

close mycur;

end;

典型游標for 迴圈

游標for迴圈示顯示游標的一種快捷使用方式,它使用for迴圈依次讀取結果集中的行資料,當form迴圈開始時,游標自動開啟(不需要open),每迴圈一次系統自動讀取游標當前行的資料(不需要fetch),當退出for迴圈時,游標被自動關閉(不需要使用close)。使用游標for迴圈的時候不能使用open語句,fetch語句和close語句,否則會產生錯誤。

set serveroutput on;

declare

cursor mycur(vartype number)is

select emp_no,emp_zc from cus_emp_basic

where com_no=vartype;

begin

for person in mycur(000627) loop

end loop;

end;

Oracle PL SQL游標的引入

一 定義 游標,也叫游標,就是乙個結果集 result set 二 語法 cursor 游標名 引數名 資料型別 引數名 資料型別 is select 語句 三 游標用法 1 定義游標 cursor c1 is select ename from emp 2 開啟游標執行查詢 open c1 3 取...

ORACLE PL SQL 基礎2 游標的學習

游標學習 一 游標是什麼 游標字面理解就是游動的游標。用資料庫語言來描述 游標是對映在結果集中一行資料上的位置實體,有了游標 使用者就可以訪問結果集中的任意一行資料了,將游標放置到某行後,即可對該行資料進行操作,例如提取當前 行的資料等等。二 游標的分類 顯式游標和隱式游標 顯示游標的使用需要4步 ...

Oracle PL SQL游標的使用方法

演示隱式游標,系統自動宣告,自動開啟,自動使用並且自動關閉 begin update emp set sal 1000 dbms output.put line 影響的行數 sql rowcount end rollback 游標的使用方法 第一步 宣告游標 第二步 開啟游標 第三步 使用游標進行迴...