title: How to pass OLD, NEW and identifiers to EXECUTE in a trigger function?
body: <p>I'm starting and trying some things in a new database, and am encountering a problem. I'm new in PostgreSQL.</p>
  
  <p>I'm trying to create a history for the change of values in a column of a users table. The idea is simple. Whenever there is an update, a new record is inserted in another table (which represents the history).</p>
  
  <pre><code>DROP FUNCTION IF EXISTS LOCA_APP.FUNC_HISTORICO_MOD_USUARIOS() CASCADE;
  CREATE OR REPLACE FUNCTION LOCA_APP.FUNC_HISTORICO_MOD_USUARIOS() RETURNS TRIGGER
  AS $$ 
  BEGIN
      EXECUTE 'INSERT INTO LOCA_APP.TB_MODIFICACOES (
          MOD_MOMENTO ,             -- Translated to: Moment
          MOD_VALOR_ANTERIOR ,      -- Translated to: Old value
          MOD_VALOR_ATUAL ,         -- Translated to: New value
          MOD_USUARIO ,             -- Translated to: User (ID)
          MOD_DADO)                 -- Translated to: Data (Column Name - ID)
      VALUES(
          now() , 
          OLD.' || TG_ARGV[0] || ' , 
          NEW.' || TG_ARGV[0] || ' , 
          '|| TG_RELID || ' ,
          (SELECT DAD_ID FROM LOCA_APP.TB_DADOS WHERE DAD_NOME ILIKE ''' || TG_ARGV[0] || ''') );';
  END $$ LANGUAGE plpgsql;
  
  DROP TRIGGER IF EXISTS TRIG_HISTORICO_USU_ID ON LOCA_APP.TB_USUARIOS CASCADE;
  CREATE TRIGGER TRIG_HISTORICO_USU_ID AFTER UPDATE OF USU_ID ON LOCA_APP.TB_USUARIOS
  FOR EACH ROW EXECUTE PROCEDURE LOCA_APP.FUNC_HISTORICO_MOD_USUARIOS('USU_ID');
  </code></pre>
  
  <p><strong>Note:</strong> <code>EXECUTE</code> comments were put to better understanding here. The original code does not have these comments.</p>
  
  <p>The pgAdmin is telling me:</p>
  
  <blockquote>
  <pre><code>ERROR:  missing FROM-clause entry for table "old"
  LINE 9:   OLD.USU_NASCIMENTO , 
            ^
  QUERY:  INSERT INTO LOCA_APP.TB_MODIFICACOES (
        MOD_MOMENTO ,
        MOD_VALOR_ANTERIOR ,
        MOD_VALOR_ATUAL ,
        MOD_USUARIO , 
        MOD_DADO)
    VALUES(
        now() , 
        OLD.USU_NASCIMENTO , 
        NEW.USU_NASCIMENTO , 
        22664 ,
        (SELECT DAD_ID FROM LOCA_APP.TB_DADOS WHERE DAD_NOME ILIKE 'USU_NASCIMENTO') );
  CONTEXT:  PL/pgSQL function loca_app.func_historico_mod_usuarios() line 3 at EXECUTE
  
  ********** Error **********
  
  ERROR: missing FROM-clause entry for table "old"
  SQL state: 42P01
  Context: PL/pgSQL function loca_app.func_historico_mod_usuarios() line 3 at EXECUTE
  </code></pre>
  </blockquote>
  
  <p>I have a single schema named <code>LOCA_APP</code> in my database, and my PostgreSQL version is <strong>9.5</strong>.</p>
  
  <p>Can anyone explain what's wrong?</p>