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;
share

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;
share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.