加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – postgres中的递归函数

发布时间:2020-12-13 15:56:59 所属栏目:百科 来源:网络整理
导读:如何将下面的查询映射到postgres函数. WITH RECURSIVE source (counter,product) AS (SELECT1,1UNION ALLSELECTcounter + 1,product * (counter + 1)FROM sourceWHEREcounter 10)SELECT counter,product FROM source; 我是postgres的新手.我想使用PL / pgsql
如何将下面的查询映射到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 ();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读