1
我正在寫一個PostgreSQL遞歸函數,它返回一組記錄,但我不知道它的正確語法。這裏的遞歸表是垂直包含列如下: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獲得垂直的所有孩子的):
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;
能否請你幫我糾正呢?非常感謝!