PL SQL Cursor游標的基本使用

2021-06-26 22:28:40 字數 2277 閱讀 1316

cursor:游標是sql的乙個記憶體工作區,由系統或使用者以變數的形式定義。游標的作用就是用於臨時儲存從資料庫中提取的資料塊。

cursor型別包含三種: 靜態游標:分為顯式(explicit)游標和隱式(implicit)游標;ref游標:是一種引用型別,類似於指標。

顯式游標

1) 顯式cursor的屬性包含: 

游標的屬性   返回值型別   意義  

%rowcount   整型  獲得fetch語句返回的資料行數  

%found  布林型 最近的fetch語句返回一行資料則為真,否則為假  

%notfound   布林型 與%found屬性返回值相反  

%isopen 布林型 游標已經開啟時值為真,否則為假  

2) 對於顯式游標的運用分為四個步驟: 

a 定義游標---cursor  [cursor name]  is; 

b 開啟游標---open  [cursor name]; 

c  運算元據---fetch  [cursor name] 

d  關閉游標---close [cursor name] 

游標一般格式:

declare 游標名稱 cursor for select 欄位1,欄位2,欄位3,... from 表名 where ...

open 游標名稱

fetch next from 游標名稱 into 變數名1,變數名2,變數名3,...

while @@fetch_status=0

begin

sql語句執行過程... ...

fetch next from 游標名稱 into 變數名1,變數名2,變數名3,...

endclose 游標名稱

deallocate 游標名稱 (刪除游標)

cursor 游標示例1

set serveroutput on;

declare

-- 宣告變數為資料表列的型別

v_empno emp.empno%type;

--通過%type取emp表的empno的型別

v_ename emp.ename%type;

--宣告乙個游標對應乙個查詢

cursor v_emp_cursor

is select empno,ename

from emp order by ename;

begin

-- 從游標中獲取資料

open v_emp_cursor;

loop

--從游標中取出一行存入變數

--取出以後,游標下移

fetch v_emp_cursor

into v_empno, v_ename;

--退出條件

exit when v_emp_cursor%notfound;

--列印輸出

dbms_output

.put_line(v_empno||','||v_ename);

end loop;

close v_emp_cursor;

end;

cursor示例2

table1結構如下

id int

name varchar(50)

declare @id int

declare @name varchar(50)

declare cursor1 cursor for --定義游標cursor1

select * from table1 --使用游標的物件(跟據需要填入select文)

open cursor1 --開啟游標

fetch next from cursor1 into @id,@name --將游標向下移1行,獲取的資料放入之前定義的變數@id,@name中

while @@fetch_status=0 --判斷是否成功獲取資料

begin

update table1 set name=name+'1'

where id=@id --進行相應處理(跟據需要填入sql文)

fetch next from cursor1 into @id,@name --將游標向下移1行

endclose cursor1 --關閉游標

deallocate cursor1

Cursor游標(游標)的使用

為了處理sql語句,oracle 將在記憶體中分配乙個區域,這就是上下文區。這個區包含了已經處理完的行數 指向被分析語句的指標,整個區是查詢語句返回的資料行集。游標就是指向上下文區控制代碼或指標。兩種游標 一 顯示游標 需要明確定義!顯示游標被用於處理返回多行資料的select 語句,游標名通過cu...

游標的使用

declare sql varchar 8000 password varchar 200 密碼 tbname varchar 500 資料庫.dbo.表名,如果不指定 dbo.表名,則匯出資料庫的所有使用者表 filename varchar 1000 匯入 匯出路徑 檔名,如果 tbname引數...

游標的使用

游標 cursor 是處理資料的一種方法,為了檢視或者處理結果集中的資料,游標提供了在結果集中一次以行或者多行前進或向後瀏覽資料的能力。我們可以把游標當作乙個指標,它可以指定結果中的任何位置,然後允許使用者對指定位置的資料進行處理。1.游標的組成 游標包含兩個部分 乙個是游標結果集 乙個是游標位置。...