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

2023-09-07 16:28:55 作者:义不容辞

I have a trigger function:

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

This works for the table "Users". Every time I delete a row from the "Users" table the database inserts a row with ("uuidKey", "dateCreated", "dateModified", "dateSynced", "username", "entityName") into the table "DeletedEntities" that I will use for syncing purposes later.

PostgreSQL 视图 函数 触发器 别名

The above works. Here's my problem I have about two dozen tables. I know I need to CREATE TRIGGER on each table, but I don't want to have to create a custom trigger function for each table. The only thing that would change from first function above is the last value in the INSERT statement within the function; instead of 'Users' it would be "Ledgers", or "Journal", or whatever.

Within a PostgreSQL trigger function, how do I get the name of the table that the OLD row belongs too?

解决方案

TG_TABLE_NAME. See the docs for other trigger arguments: http://www.postgresql.org/docs/current/static/plpgsql-trigger.html