我有以下触发器,每次将新记录插入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上的每个相关问题,但似乎仍然无法弄清楚这一点。
关于这里有什么问题的任何想法?我有什么明显的遗失?
答案 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);