postgres中的递归函数

PL-*_*000 5 postgresql plpgsql recursive-query postgresql-9.2

如何将下面的查询映射到postgres函数.

WITH RECURSIVE source (counter, product) AS (
SELECT
1, 1
UNION ALL
SELECT
counter + 1, product * (counter + 1)
FROM source
WHERE
counter < 10
)
SELECT counter, product FROM source;
Run Code Online (Sandbox Code Playgroud)

我是postgres的新手.我想使用PL/pgsql函数实现相同的功能.

kli*_*lin 5

递归函数:

create or replace function recursive_function (ct int, pr int)
returns table (counter int, product int)
language plpgsql
as $$
begin
    return query select ct, pr;
    if ct < 10 then
        return query select * from recursive_function(ct+ 1, pr * (ct+ 1));
    end if;
end $$;

select * from recursive_function (1, 1);
Run Code Online (Sandbox Code Playgroud)

循环功能:

create or replace function loop_function ()
returns table (counter int, product int)
language plpgsql
as $$
declare
    ct int;
    pr int = 1;
begin
    for ct in 1..10 loop
        pr = ct* pr;
        return query select ct, pr;
    end loop;
end $$;

select * from loop_function ();
Run Code Online (Sandbox Code Playgroud)

  • @rastapanda - Postgres有一个配置参数`max_stack_depth`,它指定服务器执行堆栈的最大深度.它的默认值(2MB)严重限制了递归函数.具有两个整数参数的简单测试递归函数达到约1000个级别的限制.阅读[文档]中的更多内容(http://www.postgresql.org/docs/9.4/static/runtime-config-resource.html). (3认同)