编辑:我已将更新的代码添加到我的帖子中,但缺少 return null
在 IF block 之外
我有一个表正在处理
最新的数据,并且想添加一个触发器来对其进行更新,以便我可以记录对另一个表中特定列所做的更改历史
。我运行此代码来创建一个触发器函数并对其进行测试,但出现错误
SQL Error [2F005]: ERROR: control reached end of trigger procedure without RETURN
Where: PL/pgSQL function update_history()
我的代码:
-- create function for updates to track history
CREATE function update_history ()
RETURNS TRIGGER
as $$
BEGIN
IF NEW.discipline <> OLD.discipline THEN
INSERT INTO history
(ShiftId, fieldName, OldValue, NewValue)
VALUES(New.shift_id, 'discipline', OLD.discipline, NEW.discipline);
END IF;
return null; -- notice return outside the IF block
END;
$$
language plpgsql;
-- create trigger for my table after updates are made to the working table
create trigger update_history_trigger
after update on working
for each row execute PROCEDURE update_history();
最佳答案
当条件不满足时,您的函数无法到达 RETURN
语句。将语句放在 IF
block 之外。返回值将被忽略,您可以使用 NULL
代替 NEW
。
CREATE FUNCTION update_history ()
RETURNS TRIGGER
AS $$
BEGIN
IF NEW.discipline <> OLD.discipline THEN
INSERT INTO history (ShiftId, fieldName, OldValue, NewValue)
VALUES(NEW.shift_id, 'discipline', OLD.discipline, NEW.discipline);
END IF;
RETURN NULL;
END;
$$
LANGUAGE plpgsql;
The return value of a row-level trigger fired AFTER or a statement-level trigger fired BEFORE or AFTER is always ignored; it might as well be null.
关于postgresql 触发器错误控制到达触发器末尾而没有 RETURN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56693881/