微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

postgresql – postgres中的递归函数

如何将下面的查询映射到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函数实现相同的功能.

解决方法

递归函数

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐