PostgreSQL 教程: PL/pgSQL continue 语句

八月 22, 2023

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

PL/pgSQL continue 语句简介

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

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

continue [loop_label] [when condition]

在此语法中,loop_labelwhen 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加一。如果counter大于10,则退出循环。如果counter是偶数,则跳过当前迭代。

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

概括

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