PostgreSQL递归函数返回记录集

时间:2013-03-01 05:53:57

标签: postgresql recursion sql-function

我正在编写一个PostgreSQL递归函数,它返回一组记录,但我不知道它的正确语法。这里的递归表是Vertical,其中包含以下列:

CREATE TABLE vertical
(
  id serial NOT NULL,
  name character varying(100) NOT NULL,
  insert_timestamp timestamp without time zone NOT NULL DEFAULT now(),
  deleted smallint NOT NULL DEFAULT 0,
  parent_id integer, // refer to another Vertical
  locations character varying(200),
  level smallint NOT NULL DEFAULT 1,
  CONSTRAINT vertical_pkey PRIMARY KEY (id ),
  CONSTRAINT vertical_parent_fkey FOREIGN KEY (parent_id)
      REFERENCES vertical (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT name_ukey UNIQUE (name )
)

这是我的SQL语句(按指定的id获取Vertical的所有子项):

CREATE FUNCTION getAllVerticalChilds(verticalId integer) RETURNS SETOF RECORD AS 
$BODY$
BEGIN
   WITH RECURSIVE childs(id, name, parent_id, level) AS (
   SELECT child.id, child.name, child.parent_id, child.level
   FROM vertical child
   WHERE child.parent_id = verticalId
   UNION ALL
   SELECT parent.id, parent.name, parent.parent_id, parent.level
   FROM childs child
   INNER JOIN vertical parent ON parent.parent_id = child.id where parent.deleted=0
   )
   SELECT id, name, parent_id, level
   FROM childs;
END
$BODY$
LANGUAGE plpgsql VOLATILE;
你可以帮我纠正一下吗?非常感谢你!

1 个答案:

答案 0 :(得分:5)

在postgresql中,你必须使用语句RETURN,如果你可以从函数推送一些。在你的情况下可能是RETURN QUERY ......

BEGIN
  RETURN QUERY WITH RECURSIVE ...
END

如果将函数声明为TABLE函数

,则函数的用法将更加用户友好
CREATE OR REPLACE FUNCTION xx(..) RETURNS TABLE(a int, b int, ...)

这个函数的用法是(PostgreSQL没有语句CALL)

SELECT * FROM xx(..)