Dynamic query in trigger function in PostgreSQL

2019-07-22 20:11发布

问题:

I am trying to execute a dynamic query in a trigger function but I keep getting the Missing FROM-clause entry for table "new"

Why does the error occur and how can I fix it?

CREATE OR REPLACE FUNCTION "Site"."UpdateAncestorModified"()
  RETURNS trigger AS
$BODY$BEGIN
    EXECUTE
        format
        ('
            UPDATE 
                "' || TG_TABLE_SCHEMA || '"."' || TG_TABLE_NAME || '" 
            SET
                modified = NEW.modified
            WHERE
                id = NEW."ancestorId"
            AND
                modified <> NEW.modified
        ')
    USING
        NEW;
    RETURN NEW;
END$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

回答1:

I had to change the NEW to the ($1) since it is the reference to the first bound parameter.

The correct query is:

CREATE OR REPLACE FUNCTION "Site"."UpdateAncestorModified"()
  RETURNS trigger AS
$BODY$BEGIN
    EXECUTE
        format
        ('
            UPDATE 
                "' || TG_TABLE_SCHEMA || '"."' || TG_TABLE_NAME || '" 
            SET
                modified = ($1).modified
            WHERE
                id = ($1)."ancestorId"
            AND
                modified <> ($1).modified
        ')
    USING
        NEW;
    RETURN NEW;
END$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;