postgresql 触发器错误控制到达触发器末尾而没有 RETURN

标签 postgresql plpgsql database-trigger

编辑:我已将更新的代码添加到我的帖子中,但缺少 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 documentation:

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/

相关文章:

Oracle 12c 在带有外键的表上使用 onDelete 触发器和 onDelete 级联 setNull 抛出 ORA-00600 : Internal Errorcode, 参数:[13001]

django - 迁移日期时间 w。 PostgreSQL 中的时区到 UTC 时区以使用 Django 1.4

postgresql - 什么是 "non-SETOF function"?

sql - 检查表在运行时是否为空

postgresql-9.1 - PostgreSQL 触发器中的唯一约束冲突

mysql - 更新触发器不适用于 json 数据类型

postgresql - 从 postgresQL 中的字符串中提取单词

sql - 与 * 一起使用

sql - Rails 4 内部连接在同一张 table 上

postgresql - 函数或过程名称的别名