PostgreSQL 教程: PL/pgSQL while 循环

八月 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的计算结果为falsenull。否则,您将陷入无限循环。

由于该while循环在执行statements之前会检测condition,因此该while循环有时称为预测试循环。

下面的流程图说明了该while循环语句。

PL/pgSQL WHILE loop

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 时执行代码块。

了解更多

PostgreSQL PL/pgSQL 教程