递归函数中“array_append”处或附近的语法错误

时间:2014-05-13 22:03:55

标签: sql postgresql plpgsql common-table-expression recursive-query

我是plpgsql中的新手。我的函数声明有什么问题?

它引发了错误:

ERROR:  syntax error at or near "array_append". LINE 19:
array_append(parent.childs , get_childs( ROW( child.id_pk, c...  ***

功能:

CREATE TYPE category_return AS (
    id_pk INT,
    parent_id_fk INT,
    name varchar,
    path ltree,
    childs json[]
);

------------------------

CREATE OR REPLACE FUNCTION get_childs ( parent category_return )

RETURNS category_return AS
$BODY$

DECLARE
    child record;
BEGIN
FOR child IN 
    SELECT * FROM categories c WHERE c.parent_id_fk = parent.id_pk 
LOOP
    array_append(parent.childs , get_childs( ROW( child.id_pk, child.parent_if_fk, child.name, child.path, '[]'::json[]) ) );
END LOOP

RETURN row_to_json(parent);

END;
$BODY$ LANGUAGE plpgsql;

1 个答案:

答案 0 :(得分:0)

手头的错误原因是您必须将array_append()的结果分配给变量。像:

some_var := array_append(parent.childs , get_childs( ... ));

但是整个功能以各种方式扭曲,但仍然不起作用。

没有提到你想要实现的目标,所以这是一个有根据的猜测(用递归版本更新):

CREATE OR REPLACE FUNCTION get_children (_id_pk int)
  RETURNS TABLE (id_pk int, parent_if_fk int, name text, path int[]) AS
$func$
WITH RECURSIVE cte AS (
    SELECT c.id_pk, c.parent_if_fk, c.name, ARRAY[c.id_pk] AS path
    FROM   categories c
    WHERE  c.parent_if_fk = $1

    UNION ALL
    SELECT c.id_pk, c.parent_if_fk, c.name, cte.path || c.id_pk
    FROM   cte
    JOIN   categories c ON c.parent_if_fk = c.id_pk 
    )
SELECT *
FROM   cte
ORDER  BY path
$func$ LANGUAGE sql;

返回层次结构中起始ID下方的所有行 在普通的SQL函数中使用recursive CTE。没有必要的plpgsql。