【问题标题】:how to exit the procedure if condition met in a loop PL SQL如果在循环 PL SQL 中满足条件,如何退出过程
【发布时间】:2016-12-10 15:29:44
【问题描述】:

假设我有一个 for 循环

for i in array.first .. array.last loop
 boolean := c(i) > d(i);
 if boolean --is true then
 exit the loop immediately and also exit the entire procedure

 else if the boolean is never true til the end of the loop, exit the loop
 and keep running other scripts in this procedure.

我知道'EXIT'关键字需要在循环内部才能在满足条件时退出循环。 'RETURN' 需要在循环之外才能退出程序。

但是如果我把'RETURN'放在循环之外,那么我认为无论循环的结果是什么,当循环结束时它都会退出整个过程?

【问题讨论】:

    标签: sql oracle loops plsql procedure


    【解决方案1】:

    如果你想对它说教,你应该使用 EXIT 退出循环,然后使用 RETURN 退出过程(重复任何必要的测试),从而遵循结构化编程规则“A procedure应该只有一个入口和一个出口”。在实践中,99.999% 的程序员只会在循环体中编写 RETURN,因为 A) 更清楚发生了什么(您不仅仅是退出循环,而是从过程中返回),以及 B ) 它更短。随心所欲。祝你好运。

    【讨论】:

      【解决方案2】:

      简单的循环。它被称为简单是有原因的:它简单地以 LOOP 关键字开始,以 END LOOP 语句结束。如果您在循环体中执行 EXIT、EXIT WHEN 或 RETURN(或者如果引发异常),循环将终止。

      See Oracle Magazine

      【讨论】:

        【解决方案3】:

        Tamás Kecskemétilink 之后,唯一推荐的方法是使用 while 循环,并在开头本身指定所需条件。

        以下是上述链接的摘录:

        Code Listing 5: A WHILE loop with one exit 
        
        PROCEDURE display_multiple_years (
           start_year_in   IN PLS_INTEGER
         , end_year_in     IN PLS_INTEGER)
        IS
           l_current_year PLS_INTEGER := start_year_in;
        BEGIN
           WHILE ( l_current_year <= end_year_in
                 AND total_sales_for_year (l_current_year) > 0)
           LOOP
              display_total_sales_for_year (l_current_year);
               l_current_year := l_current_year + 1;
           END LOOP;
        END display_multiple_years;
        

        【讨论】:

          【解决方案4】:

          定义一个异常,当你想退出 raise 并将异常处理为

              create procedure exit_loop_example as
              exit_loop_exception exception;
              begin
          /* previous code block */
          begin
              for i in 1..20 loop
               raise exit_loop_exception;
              end loop;
              exception when 
              exit_loop_exception then
              /* handle exit loop*/
              null;
              end;
          /* next code block */
          end;
          

          【讨论】:

            猜你喜欢
            • 2021-08-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-01-12
            • 1970-01-01
            相关资源
            最近更新 更多