我正在编写一个返回一组记录的 PostgreSQL 递归函数,但我不知道它的正确语法。这里的递归表是垂直的,其中包含以下列:
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;
你能帮我纠正这个吗?非常感谢!