PL/pgSQL 继续

总结:在本教程中,您将学习如何使用 PL/pgSQL continue 语句来控制循环。

PL/pgSQL continue 语句介绍

该 continue 语句过早地跳过循环的当前迭代并跳转到下一个。该 continue 语句可用于各种循环,包括无条件循环、 while 循环和for 循环。

下面说明了该 continue 语句的语法:

continue [loop_label] [when condition]

在此语法中, loop_label 和 when condition 是可选的。

该 loop_label 是你想跳过当前迭代循环的标签。如果省略 loop_label ,则 continue 语句将跳过循环的当前迭代。如果指定循环标签,则 continue 语句将跳过该循环的当前迭代。

的 condition 是一个布尔表达式,指定跳过循环的当前迭代的条件。如果 condition 是 true ,则 continue 将跳过当前循环迭代。

PL/pgSQL Continue 语句示例

以下示例 continue 在无条件循环中使用该语句打印出从 1 到 10 的奇数:

do
$$ declare
   counter int = 0;
begin

  loop
     counter = counter + 1;
     -- exit the loop if counter > 10
     exit when counter > 10;
     -- skip the current iteration if counter is an even number
     continue when mod(counter,2) = 0;
     -- print out the counter
     raise notice '%', counter;
  end loop;
end;
$$

输出:

NOTICE:  1
NOTICE:  3
NOTICE:  5
NOTICE:  7
NOTICE:  9

这个怎么运作。

  • 首先,初始化 counter 为零。
  • 其次,在每次迭代中将计数器加一。如果 counter 大于 10,则退出循环。如果 counter 是偶数,则跳过当前迭代。

在 mod(counter,2) 返回的除法的余 counter 两。如果为零,则计数器为偶数。 continue 语句和语句之间的所有语句 end loop 都将被跳过。

概括

  • 使用该 continue 语句提前跳过当前循环迭代并开始新的循环。