23

我有一个触发功能:

CREATE OR REPLACE FUNCTION "trigger_deleteUsers"()
RETURNS trigger AS
$BODY$
BEGIN
    INSERT INTO "DeletedEntities" ("uuidKey", "dateCreated", "dateModified", "dateSynced", "username", "entityName")
         VALUES (OLD."uuidKey", OLD."dateCreated", OLD."dateModified", "dateSynced", OLD."username", 'Users');
    RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql;

CREATE TRIGGER "deleteUsers" AFTER DELETE ON "Users" FOR EACH ROW EXECUTE PROCEDURE "trigger_deleteUsers"();

这适用于“用户”表。每次我从“Users”表中删除一行时,数据库都会在“DeletedEntities”表中插入一行(“uuidKey”、“dateCreated”、“dateModified”、“dateSynced”、“username”、“entityName”)稍后我将用于同步目的。

以上工作。这是我的问题,我有大约两打桌子。我知道我需要在每个表上创建触发器,但我不想为每个表创建自定义触发器函数。唯一与上面第一个函数不同的是函数内 INSERT 语句中的最后一个值;而不是“用户”,它将是“分类帐”或“期刊”或其他任何内容。

在 PostgreSQL 触发器函数中,如何获取 OLD 行所属的表的名称?

4

2 回答 2

38

TG_TABLE_NAME。有关其他触发参数,请参阅文档:http ://www.postgresql.org/docs/current/static/plpgsql-trigger.html

于 2013-08-05T02:36:35.417 回答
4

尝试这个:

TG_TABLE_NAME::regclass::text

我在 9.4 版本中使用它,但它应该从 8.4 开始工作。

这是您进行此更改的代码:

CREATE OR REPLACE FUNCTION "trigger_deleteUsers"()
RETURNS trigger AS
$BODY$
BEGIN
  INSERT INTO "DeletedEntities" ("uuidKey", "dateCreated", "dateModified", "dateSynced", "username", "entityName")
  VALUES (OLD."uuidKey", OLD."dateCreated", OLD."dateModified", "dateSynced", OLD."username", TG_TABLE_NAME::regclass::text);

  RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql;

CREATE TRIGGER "deleteUsers" AFTER DELETE ON "Users" FOR EACH ROW EXECUTE 
PROCEDURE "trigger_deleteUsers"();

让我知道它是否有帮助!

于 2018-07-14T12:26:36.273 回答