八月 22, 2023
摘要:在本教程中,您将学习如何使用 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
加一。如果counter
大于10,则退出循环。如果counter
是偶数,则跳过当前迭代。
mod(counter,2)
返回counter
除以 2 的余数。如果为零,则counter
为偶数。continue
语句和end loop
之间的所有语句都将被跳过。
总结
使用continue
语句提前跳过当前循环迭代并开始新的迭代。