【问题标题】:Recursive function in postgrespostgres中的递归函数
【发布时间】:2014-05-06 12:11:24
【问题描述】:

如何将下面的查询映射到 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;

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

【问题讨论】:

标签: postgresql plpgsql postgresql-9.2 recursive-query


【解决方案1】:

递归函数:

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);

循环函数:

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 ();

【讨论】:

  • 如果遍历深度嵌套的结构,使用递归样式是否可能导致堆栈溢出?
  • @rastapanda - Postgres 有一个配置参数max_stack_depth,它指定服务器执行堆栈的最大深度。它的默认值 (2MB) 严重限制了递归函数。一个带有两个整数参数的简单测试递归函数达到了大约 1000 级的限制。在the documentation 中阅读更多信息。
猜你喜欢
  • 2014-02-26
  • 1970-01-01
  • 2013-01-07
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多