函数可以检测触发事件类型吗? [英] Can a function detect the trigger event type?
问题描述
我正在使用函数
CREATE FUNCTION myfunc() RETURNS trigger AS $$ ... $$ LANGUAGE plpgsql;
带有触发器,
CREATE TRIGGER mycheck BEFORE INSERT OR UPDATE ON t
FOR EACH ROW EXECUTE PROCEDURE myfunc();
我现在的问题是在myfunc()
主体中表达有关事件的条件,例如plpgsql
My problem now is to express in the body of myfunc()
a condition about events, a plpgsql like
IF TRIGGER_EVENT_WAS_INSERT THEN ...doThis... END IF;
如何表达这种情况?(请参阅我是否具有"INSERT OR UPDATE"触发事件)
How to express this condition? (see that I have "INSERT OR UPDATE" trigger event)
我正在使用PostgreSQL v9.1.
I am using PostgreSQL v9.1.
推荐答案
是, TG_OP
. 每个文档:
TG_OP
数据类型文本;INSERT
,UPDATE
,DELETE
或TRUNCATE
的字符串,说明触发了哪个操作.
TG_OP
Data type text; a string ofINSERT
,UPDATE
,DELETE
, orTRUNCATE
telling for which operation the trigger was fired.
注意每种情况下的返回.有时您想要RETURN NEW
,如果DELETE
则未定义,反之亦然.如果它变得太复杂,则将其分为多个触发器,分别在单独的事件上调用.
Careful what you return in each case. Sometimes you want to RETURN NEW
, which is not defined in case of a DELETE
or vice versa. If it gets too complex, rather split into multiple triggers, called on separate events.
示例:
IF TG_OP = 'DELETE' THEN
-- do something
RETURN OLD; -- depends!
ELSIF TG_OP = 'UPDATE' THEN
-- do something
RETURN NEW; -- depends!
END IF;
这篇关于函数可以检测触发事件类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!