PL/pgSQL While 循环

在本教程中,您将了解 PL/pgSQL while 循环语句。

摘要:在本教程中,您将了解 PL/pgSQL while 循环语句。

PL/pgSQL while 循环介绍

该 while 循环语句执行的代码块,直到条件计算为 false 。

[ <<label>> ]
while condition loop
   statements;
end loop;

在此语法中,PostgreSQL condition 在执行 statements .

如果条件为真,则执行 statements . 每次迭代后, while 循环都会 codition 再次评估。

在 while 循环体内部,您需要更改某些变量的值以在某些点上生成 condition false 或 null 。否则,您将有一个无限循环。

因为 while 循环 condition 在执行之前测试 statements ,所以 while 循环有时被称为预测试循环。

以下流程图说明了 while 循环语句。

PL/pgSQL 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。
  • 其次,只要小于5 ,就用 while loop语句显示当前的值 counter 。在每次迭代中,将值 counter 加1。5 次迭代后,结果 counter 为 5,因此 while 循环终止。

在本教程中,您学习了如何使用 PL/pgSQL while 循环语句只要条件为真就执行代码块。