SQL 在plpgsql的循环中递增一个数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13770869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Incrementing a number in a loop in plpgsql
提问by CQM
I couldn't find this immediately from the examples. I want to increment a variable in a loop, in a function.
我无法立即从示例中找到这一点。我想在一个循环中增加一个变量,在一个函数中。
For instance:
例如:
DECLARE
iterator float4;
BEGIN
iterator = 1;
while iterator < 999
.....
iterator ++;
END;
How would this be done?
这将如何完成?
I was looking at this document about flow control:
http://www.postgresql.org/docs/8.4/static/plpgsql-control-structures.html
我正在查看有关流量控制的文档:http:
//www.postgresql.org/docs/8.4/static/plpgsql-control-structures.html
And none of them seem to be relevant for me, unless these are absolutely the only ways to simulate incrementing a variable.
它们似乎都与我无关,除非这些绝对是模拟增加变量的唯一方法。
回答by Erwin Brandstetter
To increment a variable in plpgsql:
在 plpgsql 中增加一个变量:
iterator := iterator + 1;
There is no ++operator.
没有++运营商。
About the assignment operator in plpgsql:
关于 plpgsql 中的赋值运算符:
Correct syntax for loops in PL/pgSQL in the manual.
Your code fragment would work like this:
你的代码片段会像这样工作:
DECLARE
iterator float4 := 1; -- we can init at declaration time
BEGIN
WHILE iterator < 999
LOOP
iterator := iterator + 1;
-- do stuff
END LOOP;
END;
Simpler, faster alternative with a FORloop:
使用FOR循环更简单、更快的替代方案:
FOR i in 1 .. 999 -- i is integer automatically, not float4
LOOP
-- do stuff
END LOOP;
The variable
nameis automatically defined as typeintegerand exists only inside the loop (any existing definition of the variable name is ignored within the loop).
变量
name自动定义为类型integer并且仅存在于循环内(循环内忽略变量名的任何现有定义)。
回答by albfan
For a sscce
对于一个sscce
DO $$
DECLARE
counter INTEGER := 0 ;
BEGIN
WHILE counter <= 5 LOOP
counter := counter + 1 ;
RAISE NOTICE 'Counter: %', counter;
END LOOP ;
END; $$
if you want to avoid declare variable (more concise)
如果你想避免声明变量(更简洁)
DO $$
BEGIN
FOR counter IN 1..5 LOOP
RAISE NOTICE 'Counter: %', counter;
END LOOP;
END; $$

