有如下代碼:
declare
--
query emp
.
name
cursor cur_emp
is
select empno
,
ename
,
job
from emp
where empno
=
7369
for
update of ename
;
begin
for
return_cur in cur_emp
loop
update emp
set ename
=
'LHG'
where current of cur_emp
;
end loop
;
end
;
其中的for update of ename
意思是給表中的行加鎖,經過測試,後面的ename可以寫成該表中的任何欄位,因為oracle中鎖的最低層級是行鎖,不存在給欄位加鎖。
下面是行鎖的作用:
1.行鎖開始於一個CURSOR的OPEN,結束於一個提交COMMIT或ROLLBACK,而並不是結束於一個CURSOR的結束(CLOSE)。
2.當在一個CURSOR中對某個表的行加鎖,那麼如果在這個SESSION中用另一個CURSOR操作該行記錄時候會等待第一個cursor的完成提交,直到第一個cursor提交完成之後,第二個cursor中對改行的操作才會開始執行。
3.當第一個cursor中的由於操作錯誤而不能提交時候,第二個cursor將會一直等待下去,這樣就形成了死結。預防這種情況發生的方法是在for update of ename 之後指定NOWAIT選項,這樣的話,當第二個cursor不會一直等待下去,而是出現
ORA-00054 [resource busy and acquire with NOWAIT specified]
的
訊息。
4.既然for update of後面的欄位是隨便那個欄位都可以,那麼可不可以不寫呢?如果你沒必要指定NOWAIT選項,那麼後面的欄位就可以不寫;如果你必須指定NOWAIT選項,則必須指定至少一個欄位。
5.還有一種方法是用ROWID
替代WHERE CURRENT OF YOUR_CURSOR_NAME
語句。
如下代碼:
declare
--
query emp
.
name
cursor cur_emp
is
select a
.
deptno
,
a
.
dname
,
a
.
rowid
,
b
.
rowid rowid_1
from dept a
,
emp b
where empno
=
7369
and
a
.
deptno
=
b
.
deptno
for
update nowait
;
--
local variables
v_deptno dept
.
deptno
%
type
;
v_dname dept
.
dname
%
type
;
v_rowid rowid
;
v_rowid_1 rowid
;
begin
open cur_emp
;
loop
fetch cur_emp into v_deptno
,
v_dname
,
v_rowid
,
v_rowid_1
;
exit
when cur_emp
%
notfound
;
update dept
set dname
=
'abc'
where rowid
=
v_rowid
;
update emp
set ename
=
'frank'
where rowid
=
v_rowid_1
;
end loop
;
close cur_emp
;
commit
;
exception
when others then
rollback
;
raise
;
end
;
由此,推薦的for update的習慣是:
NOWAIT
定然跟FOR UPDATE
之後。
直接用ROWID
替代WHERE CURRENT OF YOUR_CURSOR_NAME
語句,
尤其在相對繁習的程式裡頭。
COMMIT
必需存在程式結尾。以防死結成形。
EXCEPTION
裡的ROLLBACK
是最基本的需要。