什么时候应该嵌套PL/SQL BEGIN ... END块? [英] When should I nest PL/SQL BEGIN...END blocks?
问题描述
我似乎一直在随意地将BEGIN ... END块中的代码分段分组.通常,当我使用一个较长的存储过程并且需要一个临时变量时,我将只在那部分代码中声明它.当我要识别并处理为特定代码段引发的异常时,我也会这样做.
I've been somewhat haphazardly grouping subsections of code in BEGIN...END blocks when it seems right. Mostly when I'm working on a longer stored procedure and there's a need for a temporary variable in one spot I'll declare it just for that portion of the code. I also do this when I want to identify and handle exceptions thrown for a specific piece of code.
为什么要在一个过程,函数或另一个更大的PL/SQL块中嵌套块?还有其他原因吗?
Any other reasons why one should nest blocks within a procedure, function or another larger block of PL/SQL?
推荐答案
当您想像这样在本地处理异常时:
When you want to handle exceptions locally like this:
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;
在此示例中,处理了异常,然后我们继续处理下一个雇员.
In this example, the exception is handled and then we carry on and process the next employee.
另一种用法是声明范围有限的局部变量,如下所示:
Another use is to declare local variables that have limited scope like this:
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;
请介意,这通常表明您的程序太大,应该分解:
Mind you, wanting to do this is often a sign that your program is too big and should be broken up:
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;
这篇关于什么时候应该嵌套PL/SQL BEGIN ... END块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!