PostgreSQL查询没有结果数据的目的地

时间:2016-08-18 01:30:28

标签: sql postgresql

我有以下触发器,每次将新记录插入number表时,都应该将posts分配给帖子。它会找到number的最大posts作为新记录的project_id范围。

  CREATE OR REPLACE FUNCTION assign_number()
    RETURNS trigger AS
  $BODY$
  BEGIN
    SELECT coalesce(MAX(number), 0) max_number FROM posts WHERE project_id = NEW.project_id;
    NEW.number := max_number + 1;
    RETURN NEW;
  END;
  $BODY$ LANGUAGE plpgsql;

  CREATE TRIGGER post_created
    BEFORE INSERT ON posts
    FOR EACH ROW
    EXECUTE PROCEDURE assign_number();

不幸的是,我在尝试query has no destination for result data时遇到语法错误INSERT。我已经尝试了所有我能想到的内容并查看了StackOverflow上的每个相关问题,但似乎仍然无法弄清楚这一点。

关于这里有什么问题的任何想法?我有什么明显的遗失?

1 个答案:

答案 0 :(得分:2)

很明显,是的。您尚未声明变量max_number,并且未使用INTO子句:

CREATE OR REPLACE FUNCTION assign_number() RETURNS trigger AS $BODY$
DECLARE
  max_number integer;
BEGIN
  SELECT coalesce(MAX(number), 0) INTO max_number FROM posts 
  WHERE project_id = NEW.project_id;
  NEW.number := max_number + 1;
  RETURN NEW;
END;
$BODY$ LANGUAGE plpgsql;

或者,您可以不使用变量并将结果直接放入NEW.number

SELECT coalesce(MAX(number)+1, 1) INTO NEW.number FROM posts 
WHERE project_id = NEW.project_id;

甚至:

NEW.number := (SELECT coalesce(MAX(number)+1, 1) FROM posts 
               WHERE project_id = NEW.project_id);