什么时候应该嵌套PL/SQL BEGIN ... END块?

aw *_*rud 14 sql oracle plsql

当看起来正确时,我有点偶然地将BEGIN ... END块中的代码子组分组.大多数情况下,当我正在处理一个较长的存储过程并且在一个位置需要一个临时变量时,我将仅为该部分代码声明它.当我想识别和处理特定代码段抛出的异常时,我也会这样做.

为什么要在程序,函数或其他更大的PL/SQL块中嵌套块的任何其他原因?

Ton*_*ews 17

当你想在本地处理异常时,如下所示:

begin
   for emp_rec in (select * from emp) loop
      begin
         my_proc (emp_rec);
      exception
         when some_exception then
            log_error('Failed to process employee '||emp_rec.empno);
      end;
   end loop;
end;
Run Code Online (Sandbox Code Playgroud)

在此示例中,处理异常,然后我们继续并处理下一个雇员.

另一个用途是声明范围有限的局部变量,如下所示:

declare
    l_var1 integer;
    -- lots of variables
begin
   -- lots of lines of code
   ...
   for emp_rec in (select * from emp) loop
      declare
         l_localvar integer := 0;
      begin
         -- Use l_localvar
         ...
      end
   end loop;

end;
Run Code Online (Sandbox Code Playgroud)

请注意,想要这样做往往表明你的程序太大而且应该分解:

declare
   l_var1 integer;
   -- lots of variables
   ...
   procedure local_proc (emp_rec emp%rowtype):
      l_localvar integer := 0;
   begin
      -- Use l_localvar
      ...
   end
begin
   -- lots of lines of code
   ...
   for emp_rec in (select * from emp) loop
      local_proc (emp_rec);
   end loop;

end; 
Run Code Online (Sandbox Code Playgroud)