在PostgreSQL中的递归查询函数中使用PERFORM

时间:2019-02-27 16:33:48

标签: postgresql plpgsql common-table-expression postgresql-9.5

我有一个想在postgresql函数中使用的回溯查询,它应该返回一个布尔值。

CREATE OR REPLACE FUNCTION store.is_item(object1 VARCHAR(40), object2 VARCHAR(40))
RETURNS BOOLEAN AS $$
BEGIN
   WITH RECURSIVE externals AS (
   SELECT object_id, used_id
   FROM store.obj_depend
   WHERE external = true
   ), history AS (
   SELECT content_id AS id
   FROM store.minfos
   WHERE id= $2
   UNION
   SELECT externals.used_id
   FROM externals
   INNER JOIN history ON history.id = externals.object_id
   ),
   PERFORM (SELECT c.id FROM store.cinfo AS c WHERE c.id = $1 INNER JOIN history 
   ON c.id = history.id);
   RETURN FOUND;
END;
$$ LANGUAGE plpgsql;

当我尝试这样做时,出现错误syntax error at or near SELECT

1 个答案:

答案 0 :(得分:0)

PERFORM是plpgsql语句,不能在任何SQL命令中使用。

您可以像建议的@klin一样使用PERFORM,但是随后在子查询中使用CTE,并且子查询每次都返回一行。那么FOUND变量每次都应该为true。

在这种情况下,最好使用辅助变量作为目标。

CREATE OR REPLACE FUNCTION store.is_item(object1 VARCHAR(40), object2 VARCHAR(40))
RETURNS BOOLEAN AS $$
DECLARE r record;
BEGIN
  WITH RECURSIVE 
    externals AS (SELECT object_id, used_id
                    FROM store.obj_depend
                   WHERE external = true)
    history AS (SELECT content_id AS id
                  FROM store.minfos
                 WHERE id = object2
                UNION
                SELECT externals.used_id
                  FROM externals
                       INNER JOIN history ON history.id = externals.object_id)
  SELECT c.id
    FROM store.cinfo AS c 
         INNER JOIN history ON c.id = history.id
   WHERE c.id = $1 
    INTO r;
  RETURN FOUND;
END;
$$ LANGUAGE plpgsql;