某些PL / SQL过程需要花费大量时间进行评估(重新计算并更新大量数据)。
我想限制将此过程评估为单一的执行上下文的数量。
如果某个其他上下文执行它,就什么都不做......
但我不知道在PL / SQL代码中使用哪些原子操作。
注意:我担心如果服务器在程序评估的中间暂停,那么使用表行进行同步会导致数据库中的状态不一致...
答案 0 :(得分:4)
您可以使用DBMS_LOCK.request
生成唯一的锁定句柄。只有一个会话可以同时保持此锁定。如果数据库重新启动会话意外结束,则锁定将自动释放。
如果锁定将在提交期间保持不变,您决定何时请求锁定。
以下是一个例子:
SQL> CREATE OR REPLACE PROCEDURE serial IS
2 l_lock_handle VARCHAR2(128 BYTE);
3 l_lock_request INTEGER;
4 BEGIN
5 dbms_lock.allocate_unique(lockname => 'MY_SERIAL_PROC',
6 lockhandle => l_lock_handle);
7 l_lock_request := dbms_lock.request(lockhandle => l_lock_handle,
8 timeout => 5,
9 release_on_commit => FALSE);
10 CASE l_lock_request
11 WHEN 0 THEN
12 NULL; -- success
13 WHEN 1 THEN
14 raise_application_error(-20002, 'lock already reserved');
15 ELSE
16 raise_application_error(-20001, 'Lock error: ' || l_lock_request);
17 END CASE;
18 BEGIN
19 ---------- serialized block of code ----------
20 ---------- (lock will be kept accross commit) ----------
21 dbms_lock.sleep(30);
22 ---------- End of serialized code ----------
23 EXCEPTION
24 WHEN OTHERS THEN -- release lock in case of uncatched error
25 l_lock_request := dbms_lock.release(lockhandle => l_lock_handle);
26 RAISE;
27 END;
28 l_lock_request := dbms_lock.release(lockhandle => l_lock_handle);
29 END;
30 /
Procedure created
我会同时开两个课程:
Session A> exec serial;
Session B> -- Before session A ends
Session B> exec serial;
ERROR at line 1:
ORA-20002: lock already reserved
ORA-06512: at "APPS.SERIAL", line 13
ORA-06512: at line 1
PL/SQL procedure successfully completed
Session B> -- After session A ends
Session B> exec serial;
PL/SQL procedure successfully completed.