游標(cursor),也稱之為游標,從字面意思理解就是游動的游標。
游標是對映在結果集中一行資料上的位置實體。
游標是從表中檢索出
結果集,並從中每次指向一條記錄進行互動的機制。
cursor 游標名 [ (引數名 資料型別[,引數名 資料型別]...)]
is select 語句;
【示例】
無參游標:
cursor c_emp is select ename from emp;
有參游標:
cursorc_emp(v_deptno emp.deptno%type) is select ename from emp where deptno=v_deptno;
游標的屬性
返回值型別
說明%rowcount
整型獲得fetch語句返回的資料行數
%found
布林型最近的fetch語句返回一行資料則為真,否則為假
%notfound
布林型 與
%found
屬性返回值相反
%isopen
布林型游標已經開啟時值為真,否則為假
--使用游標查詢
emp表中所有員工的姓名和工資,並將其依次列印出來。
declare
--宣告乙個游標
cursor
c_emp
isselect
* from
emp;
--記錄型變數
v_emp emp%
rowtype;
begin
--開啟游標,執行查詢
open
c_emp;
--使用游標,迴圈取值
loop
--獲取游標的值放入變數的時候,必須要
into
前後要對應(數量和型別)
fetch
c_emp
into
v_emp;
exit
when
c_emp%
notfound
; --
輸出列印
dbms_output.put_line(
'員工的姓名:
'|| v_emp.ename ||
',員工的工資
'|| v_emp.sal);
endloop;
close
c_emp ;
--關閉游標,釋放資源
end;
(1)例題:顯示30部門的所有員工的編號及姓名,要求格式是 編號--姓名
declare
erow emp%rowtype;
cursor cur_1 is select * from emp where deptno=30;
begin
open cur_1;
loop
fetch cur_1 into erow;
exit when cur_1%notfound;
dbms_output.put_line(erow.empno||'-----'||erow.ename);
end loop;
close cur_1;
end;
(2)例題:顯示30部門的所有員工的編號及姓名,要求格式是 編號--姓名
(部門編號手動輸入)
declare
erow emp%rowtype;
cursor cur_2 is select * from emp where
deptno=&部門編號;
begin
open cur_2;
loop
fetch cur_2 into erow;
exit when cur_2%notfound;
dbms_output.put_line(erow.empno||'-----------'||erow.ename);
end loop;
close cur_2;
end;
(3)例題查詢
10號部門的員工的姓名和薪資
declare
cursor c_1 (v_deptno emp.deptno%type) is select ename,sal from emp where deptno=v_deptno;
v_ename emp.ename%type;
v_sal emp.sal%type;
begin
open c_1(10);
loop
fetch c_1 into v_ename,v_sal;
exit when c_1%notfound;
dbms_output.put_line(v_ename||'---'||v_sal);
end loop;
close c_1;
end;
(4)例題查詢
10 號部門的員工的姓名和薪資(部門手動輸入)
declare
cursor c_2(v_deptno emp.deptno%type) is select ename,sal from emp where deptno = v_deptno;
v_ename emp.ename%type;
v_sal emp.sal%type;
vv_deptno emp.deptno%type;
begin
vv_deptno :=&部門編號;
open c_2(vv_deptno);
loop
fetch c_2 into v_ename,v_sal;
exit when c_2%notfound;
dbms_output.put_line(v_ename||'--'||v_sal);
end loop;
close c_2;
end;
oracle游標的使用
當select語句從資料庫中返回的記錄多餘一條時,就可以使用游標 cursor 游標可以理解為一次訪問乙個的一組記錄。select語句將列提取到游標中,然後根據游標取得記錄。使用游標時需要遵從以下的5個步驟 1 宣告一些變數,用於儲存select語句返回列值 2 宣告游標,並制定select語句 3...
ORACLE游標的使用
1 游標的說明 游標是一種向包含多條資料記錄的結果集中每次讀取一行的機制,逐行處理查詢結果,以程式設計的方式訪問資料庫。可以把游標當成指標,可以指定結果集中的任何位置,然後允許使用者對指定位置的資料進行操作。sql的游標是一種臨時資料庫物件,可以臨時存放資料表中的資料行副本,也可以指向儲存在資料表中...
oracle游標的使用
游標小結 綜合使用雙層迴圈中使用游標 set serveroutput on declare cursor cdept is select deptno fromdept 10 20 30 部門的集合 dpeptno dept.deptno type 部門中員工的所有工資 cursor cemp d...