如何在Postgres函数中使用WITH?

时间:2018-11-25 01:54:57

标签: postgresql common-table-expression

如何在函数中用as编写?我想编写一个递归函数来计算汽车的重量。它给了我这样的错误: 错误:“ WITH”或附近的语法错误

create or replace function aggregateWeight(p integer)
returns int as
$$ 
begin
    if p in (select p.pid
        from parts p) then
        return (select p.weight
                from parts p)
    else
        return
        WITH RECURSIVE included_parts(pid, sid, quantity) AS (
        SELECT ps.pid, ps.sid, ps.quantity
        FROM partSubPart ps
        UNION ALL
        SELECT pr.pid, ps.sid, pr.quantity*ps.quantity
        FROM included_parts pr, partSubPart ps
        WHERE ps.pid = pr.sid
        )
        SELECT sum(pr.quantity*p.weight)
        FROM included_parts pr, parts p
        where pr.sid in (select p.pid from parts p)
        GROUP BY pid;
end;
$$ language sql;

1 个答案:

答案 0 :(得分:0)

尝试用括号将查询括起来。

您还缺少END IF;之后的ELSE