1.什麼是游標?
答:游標是系統給使用者開設的乙個資料緩衝區,存放sql語句的執行結果,
每個游標都有乙個乙個名字,使用者可以用sql語句從游標中提取資料,然後賦給變數。
2.游標分類
答:游標分為隱式游標(游標屬性)、顯示游標(游標技巧)和ref游標(游標變數);
3.隱式游標如何使用?
答:使用dml時自動建立隱式游標,它是自動宣告、自動開啟、自動關閉的,名字為sql.
屬性有:%found,%notfound,%rowcount,%isopen.
4.如何使用顯式游標?
答:顯式游標在pl/sql塊中宣告部分定義查詢,該查詢可以返回一行或多行記錄。
使用顯式游標分為四步:
(1)、宣告游標
declare
cursor mycursor is
select ename,sal from emp where deptno=10;
v_name emp.ename*type;
v_sal emp.sal%type;
begin
(2)、開啟游標
open mycursor ;
(3)、使用游標
loop
fetch mycursor into v_name,v_sal ;
exit when mycursor%notfound;
dbms_output.put_line(v_name||'->'||v_sal);
end loop;
(4)、關閉游標
close mycursor;
end;
5、使用帶引數的顯式游標。
declare cursor emp_cursor(dno number) is
select ename,sal from emp
where deptno=dno
emp_record emp_cursor%rowtype;
begin
if not emp_cursor%isopen then
open emp_cursor(20);
end if;
loop
fetch emp_cursor into emp_record
exit when emp_cursor%notfound
dbms_output.put_line(emp_record.ename||'->'||emp_record.sal);
end loop;
close emp_cursor;
end;
6、迴圈游標(不用開啟和關閉游標但需要宣告乙個與游標相同型別的游標變數)
declare cursor emp_cursor(dno number) is
select ename,sal from emp
where deptno=dno;
emp_record emp_cursor%rowtype;
begin
for emp_record in emp_cursor(10) loop
dbms_output.putline(v_name||'->'||v_sal);
end loop;
end;
7、使用游標更新行
declare
cursor emp_cursor is
select ename,sal,deptno from emp for update;--鎖定emp表,執行完後不提交或者回滾將會把當前表鎖定
emp_record emp_cursor%rowtype;
begin
if not emp_cursor%isopen then
open emp_cursor;
end if;
loop
fetch emp_cursor into emp_record;
exit when emp_cursor%notfound;
if emp_record.deptno = 30 then
update emp set sal=sal+100 where current of emp_cursor;
end if;
dbms_output.put_line(emp_record.sal);
end loop;
close emp_cursor;
end;
8、ref游標(游標變數)
declare
type my_type is ref cursor;
cv my_type;
--cv sys_refcursor;
v_lastname employee.ename%type;
query_2 varchar2(200):='select * from dept';
v_emp emp%rowtype;
v_dept dept%rowtype;
begin
open cv for
select ename from emp
where job='manager'
order by ename;
loop
fetch cv into v_lastname;
exit when cv%notfound;
dbms_output.put_line(v_lastname);
end loop;
dbms_output.put_line('----------------');
open cv for query_2;
loop
fetch cv into v_dept;
exit when cv%notfound;
dbms_output.put_line(v_dept.dname);
end loop;
close cv;
end;
oracle游標的使用
當select語句從資料庫中返回的記錄多餘一條時,就可以使用游標 cursor 游標可以理解為一次訪問乙個的一組記錄。select語句將列提取到游標中,然後根據游標取得記錄。使用游標時需要遵從以下的5個步驟 1 宣告一些變數,用於儲存select語句返回列值 2 宣告游標,並制定select語句 3...
oracle游標的使用
游標 cursor 也稱之為游標,從字面意思理解就是游動的游標。游標是對映在結果集中一行資料上的位置實體。游標是從表中檢索出 結果集,並從中每次指向一條記錄進行互動的機制。cursor 游標名 引數名 資料型別 引數名 資料型別 is select 語句 示例 無參游標 cursor c emp i...
ORACLE游標的使用
1 游標的說明 游標是一種向包含多條資料記錄的結果集中每次讀取一行的機制,逐行處理查詢結果,以程式設計的方式訪問資料庫。可以把游標當成指標,可以指定結果集中的任何位置,然後允許使用者對指定位置的資料進行操作。sql的游標是一種臨時資料庫物件,可以臨時存放資料表中的資料行副本,也可以指向儲存在資料表中...