触发动态知道事件类型
Trigger knowing the event type dynamically
对于在 INSERT
或 UPDATE
之前发生的触发器,我有大部分相同的代码,
而不是创建 2 个触发器,是否有任何方法可以知道触发器内动态发生的事件类型?
示例:
CREATE OR REPLACE FUNCTION UpsertClientLog() RETURNS TRIGGER AS $$
DECLARE action_type VARCHAR(255);
BEGIN
IF (event == 'INSERT') THEN
action_type = 'Create'
ELSE
action_type = 'Update'
END IF;
-- Same code from here on out ..
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER UPSERT_CLIENT_LOG BEFORE INSERT OR UPDATE ON client
FOR EACH ROW EXECUTE PROCEDURE UpsertClientLog();
您可以使用 special variable TO_OP
:
TG_OP
Data type text; a string of INSERT
, UPDATE
, DELETE
, or TRUNCATE
telling for which operation the trigger was fired.
对于在 INSERT
或 UPDATE
之前发生的触发器,我有大部分相同的代码,
而不是创建 2 个触发器,是否有任何方法可以知道触发器内动态发生的事件类型?
示例:
CREATE OR REPLACE FUNCTION UpsertClientLog() RETURNS TRIGGER AS $$
DECLARE action_type VARCHAR(255);
BEGIN
IF (event == 'INSERT') THEN
action_type = 'Create'
ELSE
action_type = 'Update'
END IF;
-- Same code from here on out ..
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER UPSERT_CLIENT_LOG BEFORE INSERT OR UPDATE ON client
FOR EACH ROW EXECUTE PROCEDURE UpsertClientLog();
您可以使用 special variable TO_OP
:
TG_OP
Data type text; a string of
INSERT
,UPDATE
,DELETE
, orTRUNCATE
telling for which operation the trigger was fired.