2013-03-01 154 views
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; 

能否請你幫我糾正呢?非常感謝!

回答

5

在postgresql中,如果可以從函數中推送某些函數,則必須使用語句RETURN。你的情況可能返回查詢...

BEGIN 
    RETURN QUERY WITH RECURSIVE ... 
END 

和你的函數的使用將更加人性化,如果你申報你的功能表功能

CREATE OR REPLACE FUNCTION xx(..) RETURNS TABLE(a int, b int, ...) 

這個函數的用法是( PostgreSQL沒有聲明CALL)

SELECT * FROM xx(..)