如何在PostgreSQL触发器函数中获取表名?

时间:2013-08-05 02:29:45

标签: postgresql triggers synchronization

我有一个触发功能:

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”)。我将在稍后用于同步目的。

以上作品。这是我的问题,我有大约二十几个表。我知道我需要在每个表上创建TRIGGER,但我不想为每个表创建自定义触发器函数。从上面的第一个函数改变的唯一的东西是函数内INSERT语句中的最后一个值;而不是'用户',它将是“Ledgers”,或“Journal”,或其他。

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

2 个答案:

答案 0 :(得分:18)

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

答案 1 :(得分:0)

尝试一下:

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"();

让我知道是否有帮助!