postgresql 触发器错误控制在没有 RETURN 的情况下到达触发器末尾
postgresql trigger error control reached end of trigger without RETURN
编辑:我已将更新后的代码添加到我的 post,但我缺少一个 return null
在我的 IF 块之外
我有一个包含最新数据的 table working
,我想添加一个触发器来更新它,这样我就可以在另一个 table history
。我 运行 这段代码创建了一个触发器函数并对其进行了测试,但出现错误
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
块之外。返回值将被忽略,您可以使用 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.
编辑:我已将更新后的代码添加到我的 post,但我缺少一个 return null
在我的 IF 块之外
我有一个包含最新数据的 table working
,我想添加一个触发器来更新它,这样我就可以在另一个 table history
。我 运行 这段代码创建了一个触发器函数并对其进行了测试,但出现错误
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
块之外。返回值将被忽略,您可以使用 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.