游標資料修改和游標變數

2021-09-05 10:12:18 字數 1753 閱讀 6044

修改游標資料:

如果建立的游標需要執行更新或者刪除必須帶有for update子句,for update子句會將游標提取出來的資料進行行級鎖定,這樣在本會話更新期間,其他使用者的會話就不能對當前游標中的資料進行更新操作,for update有如下兩種形式:

for update[of 列,列...]

為游標中的資料列增加行級鎖定,這樣在游標更新時,其他使用者的會話無法更新指定資料。

declare

cursor cur_emp is select * from emp where deptno = 10 for update of sal,comm;

begin

for emp_row in emp loop

update emp set sal =9999 where current of cur_emp;

end loop;

end;

for update和for update of區別

多表查詢時使用後者,指定列才能保證資料正常更新,單錶查詢時兩者作用一樣

for update nowait

在oracle中,所有的事務都是具備隔離性的,當乙個使用者會話更新資料且事務未提交時,其他的使用者會話是無法對資料進行更新的,如果此時執行游標的更新操作,難麼就會進入死鎖的狀態。為了避免游標出現死鎖的情況,可以在建立時使用for update nowait子句,如果發現所操作的資料行已經鎖定,將不會等待,立即返回。

declare

cursor cur_emp is select * from emp where deptno = 10 for update nowait;

begin

for emp_row in emp loop

update emp set sal =9999 where empno = emp_row.empno

end loop;

end;

游標變數:

在定義游標的時候不繫結具體的查詢,動態的開啟指定型別的查詢

cursor 游標變數型別名稱 is ref cursor[return 資料型別];

游標變數一定需要乙個型別定義,如果寫上了return就表示是一種強型別定義,如果不寫return就表示弱型別定義,強型別的話其查詢的語句結構必須與宣告的一直,如果是弱型別,就可以在使用的時候動態決定

在使用游標變數的時候是無法使用for迴圈的,只能使用loop迴圈

declare

type dept_ref is ref cursor return dept%rowtype; --定義強型別游標型別

cur_dept dept_ref; --定義游標變數

v_deptrow dept%rowtype; --定義行型別

begin

open cur_dept for select * from dept; --開啟游標並決定游標型別

loop

fetch cur_dept into v_deptrow; --取得游標資料

exit when cur_dept%notfound; --如果沒有資料就退出

dbms_output.put_line(cur_emp%rowcount || '部門名稱:' || v_deptrow.dname));

end loop;

close cur_dept;

end;

ORACLE 游標和游標變數的區別

如何定義游標型別 type ref type name is ref cursor return return type 宣告游標變數 cursor name ref type name 從技術底層看,兩者是相同的。普通plsql cursor在定義時是 靜態 的。而ref cursors可以動態開...

Oracle游標和游標變數的區別

oracle游標我們經常用到,下面介紹oracle游標和游標變數的區別。oracle游標是資料庫中乙個命名的工作區,當游標被宣告後,他就與乙個固定的sql想關聯,在編譯時刻是已知的,是靜態的,它永遠指向乙個相同的查詢工作區。游標變數可以在執行時刻與不同的sql語句關聯,在執行時可以取不同的sql語句...

游標修改資料

declare updateemtinca rcursor cursor scroll 宣告乙個游標 for select emtincar.id as emtincar id,case when b.yieldtransitstatetype id is null then 3 else b.yi...