八月 20, 2023
摘要:在本教程中,您将了解 PL/pgSQL 中的while
循环语句。
目录
PL/pgSQL while 循环简介
while
循环语句执行代码块,直到条件计算结果为false
。
[ <<label>> ]
while condition loop
statements;
end loop;
在此语法中,PostgreSQL 在执行statements
前计算condition
。
如果条件为真,则执行statements
。每次迭代后,while
循环都会再次计算codition
。
在while
循环体内,您需要更改某些变量的值,以在某些时间点上让condition
的计算结果为false
或null
。否则,您将陷入无限循环。
由于该while
循环在执行statements
之前会检测condition
,因此该while
循环有时称为预测试循环。
下面的流程图说明了该while
循环语句。
PL/pgSQL while 循环示例
以下示例使用while
循环语句来显示计数器的值:
do $$
declare
counter integer := 0;
begin
while counter < 5 loop
raise notice 'Counter %', counter;
counter := counter + 1;
end loop;
end$$;
输出:
NOTICE: Counter 0
NOTICE: Counter 1
NOTICE: Counter 2
NOTICE: Counter 3
NOTICE: Counter 4
怎么运行的。
- 首先,声明
counter
变量并将其值初始化为 0。 - 其次,使用
while
循环语句,只要小于 5 就显示counter
的当前值。在每次迭代中,将counter
的值增加 1。5 次迭代后,counter
值为 5,因此while
循环终止。
在本教程中,您学习了如何使用 PL/pgSQL 的 while 循环语句在条件为 true 时执行代码块。