游標的簡單使用

2021-08-31 12:05:01 字數 2368 閱讀 3477

游標是從表中提取的資料以臨時表的形式存放記憶體中,游標中有乙個資料指標,預設指向的是第一條記錄。利用fetch語句移動該指標,從而對游標中的資料進行操作。

語法:

cursor 游標名 is select 語句; 

--select是建立游標的資料表查詢命令.

開啟游標:

open 游標名;
開啟游標相當於執行了下面兩個動作:

a.將符合條件的記錄送入記憶體

b.將指標指向第一條記錄

移動指標,將資料提取出來:

fetch 游標名 into 變數名1,變數名2,.......;

fetch 游標名 into 記錄型變數名;

關閉游標:

close 游標名;
游標的屬性:

--使用方法:游標名%屬性 

cursor%isopen

--測試游標是否開啟,如果沒有開啟游標就使用fetch語句將提示錯誤

cursor%found屬性

--測試前乙個fetch語句是否有資料,有值將返回true,否則為false

cursor%notfound屬性

--%found屬性的反邏輯,常被用於退出迴圈,判斷游標是否沒有資料

cursor%rowcount屬性

--用於返回游標的資料行數,若返回值為0,表明游標已經開啟,但沒有提取出資料.

游標的簡單運用:首先建立乙個表employee,包含以下字段,往表裡插入一些資料;

1.取表裡滿足條件的第一條記錄:

declare

tempsal employee.salary%type;

cursor mycursor is

select * from employee where salary2.取滿足條件的所有記錄需要用到迴圈,讓游標往下移動取值:

declare

tempsal employee.salary%type;

cursor mycursor is

select * from employee where salary3.取滿足條件的前面幾條記錄,迴圈時用到for i in 1..n loop(n自己確定):

declare

tempsal employee.salary%type;

cursor mycursor is

select * from employee where salary4.利用mycursor%rowcount確定跳出迴圈的時間,%rowcount的值要<=滿足要求的總記錄數

declare

tempsal employee.salary%type;

cursor mycursor is

select * from employee where salary注意exit when mycursor%rowcount=4的位置:

如果在上面,結果只顯示%rowcount-1條記錄,原因是只要%rowcount=?後,迴圈就提前跳出了,沒有執行下面的輸出語句。

如果在下面,先執行輸出語句再判斷,判斷為false就跳出迴圈了,輸出的結果數字%rowcount個。

5.帶引數的游標

declare

cursor mycur(vartype number) is select * from employee where employee.salary=vartype;

begin

for emp in mycur(2000) loop

dbms_output.put_line(emp.empid||','||emp.salary);

end loop;

end;

mycur(2000)是將工資為2000的所有記錄放在臨時表中,emp為變數名,for emp in mycur(2000) loop是迴圈取臨時表裡的資料。

6.儲存過程中使用游標

create or replace procedure emp_pro_cur 

ascursor cur is select * from employee where employee.empname like 'd%';

begin

for emp in cur loop --這裡for迴圈,不需要使用fetch移動游標指標

dbms_output.put_line(emp.empname);

end loop;

end;

--呼叫儲存過程

call emp_pro_cur();

游標的簡單使用

create table tablea tid int not null,mid int not null go insert into tablea values 2,2 insert into tablea values 3,3 insert into tablea values 4,4 ins...

游標的簡單使用

create table tablea tid int not null,mid int not null go insert into tablea values 2,2 insert into tablea values 3,3 insert into tablea values 4,4 ins...

SQL 游標的簡單使用

sql 游標的簡單使用例子 declare cur monthlypolicy cursor for select distinct t policyproperty.policyname from t policyproperty inner join t policy on t policypr...