0

我有以下 plpgsql 函数,该函数在 pg 8.3 及更高版本上运行良好,但我需要将其转换回 pg 8.1 数据库并且我无法缝合以使其正确。

有小费吗?我需要摆脱“返回查询”,因为它尚未在 8.1 中引入......

CREATE OR REPLACE FUNCTION specie_children (specie_id INT, self BOOLEAN)
      RETURNS SETOF specie AS
    $BODY$
    DECLARE
      r specie%ROWTYPE;
    BEGIN
      IF self THEN
        RETURN QUERY SELECT * FROM specie WHERE specieid = specie_id;
      END IF;
      FOR r IN SELECT * FROM specie WHERE parent = specie_id
      LOOP
        RETURN NEXT r;
        RETURN QUERY SELECT * FROM specie_children(r.specieid, FALSE);
      END LOOP;
      RETURN;
    END
    $BODY$
    LANGUAGE 'plpgsql';

我该如何翻译这个?

4

2 回答 2

1
RETURN QUERY SELECT * FROM specie_children(r.specieid, FALSE);

可以改写为

for r2 in select * from specie_children(r.specieid, FALSE)
loop
    return next r2
end loop
于 2012-07-24T10:06:23.713 回答
0

快速演示。基本上@maniek 已经提供了答案。

测试表:

CREATE TEMP TABLE specie(specieid int, parent int);
INSERT INTO specie VALUES
 (1,0), (2,0), (3,0)
,(11,1), (12,1), (13,1)
,(111,11), (112,11), (113,11);

改写函数:

CREATE OR REPLACE FUNCTION specie_children (specie_id INT, self BOOLEAN)
  RETURNS SETOF specie AS
$BODY$
DECLARE
   r specie%ROWTYPE;
BEGIN
IF self THEN
   FOR r IN SELECT * FROM specie WHERE specieid = $1
   LOOP
      RETURN NEXT r;
   END LOOP;
END IF;

FOR r IN SELECT * FROM specie WHERE parent = $1
LOOP
   RETURN NEXT r;
   FOR r IN SELECT * FROM specie_children(r.specieid, FALSE)
   LOOP
      RETURN NEXT r;
   END LOOP;
END LOOP;

RETURN;
END;
$BODY$
LANGUAGE plpgsql;

称呼:

SELECT * FROM specie_children (1, true);

回报:

specieid | parent
---------+-------
1        | 0
11       | 1
111      | 11
112      | 11
113      | 11
12       | 1
13       | 1
于 2012-07-24T13:41:30.070 回答