0

我有一个程序应该一次执行一个。我的意思是当程序正在执行时,其他进程/用户不应该能够执行相同的程序。

只有在程序执行后,下一次才能执行

请帮忙

4

1 回答 1

2

要序列化过程的执行,您可以使用dbms_lock包,特别是该包allocate_unique()release()过程和request()功能。这是一个示例,我们在其中创建了一个包来规范锁获取过程:

包装规格

create or replace package proc_lock as
  function request_lock( p_lock_name   in varchar2) return varchar2;
  procedure release_lock(p_l_handle in varchar2);
end;

包体

create or replace package body proc_lock as
  function request_lock( p_lock_name   in varchar2) return varchar2
  is
    l_request     number;
    l_lock_handle varchar2(1000);
  begin
    dbms_lock.allocate_unique(p_lock_name, l_lock_handle);
    -- waits 5 sec trying to acquire a lock
    l_request := dbms_lock.request(l_lock_handle, timeout=>5);
    if l_request <> 0
    then
      raise_application_error(-20001, 'Lock cannot be acquired.');
    end if;
    return l_lock_handle;
  end;

  procedure release_lock(p_l_handle in varchar2)
  is
  begin
    if dbms_lock.release(p_l_handle) > 0
    then
      raise_application_error(-20000, 'Cannot release lock');
    end if;
  end;
end;

这是一个简单的过程,应该序列化

create or replace procedure test_proc
is
  l_handle       varchar2(1000);   -- lock handle
begin
  -- trying to acquire a lock
  l_handle := proc_lock.request_lock('test');
  -- here goes all usefull work that this procedure 
  -- would do if lock acquired successfully 
  dbms_output.put_line('procedure is working');
  -- mimic large amount of work
  dbms_lock.sleep(10);
  dbms_output.put_line('procedure is done');
  -- release the lock after work is done
  proc_lock.release_lock(l_handle);
end;

测试用例:

--Session #1
SQL> exec test_proc;

--Session #2 at the same time
SQL> exec test_proc;

BEGIN test_proc; END;

*
ERROR at line 1:
ORA-20001: Lock cannot be acquired. 
ORA-06512: at "HR.PROC_LOCK", line 11 
ORA-06512: at "HR.TEST_PROC", line 6 
ORA-06512: at line 1 

--Session #1
SQL> exec test_proc;
procedure is working                                                            
procedure is done                                                               

PL/SQL procedure successfully completed.

了解有关dbms_lock包装的更多信息。

于 2013-09-20T18:02:02.797 回答