Function taking a string as table and column name I'm trying to write a function that will create a new column in a participation table based on the presence of a id in survey_name table:

CREATE OR REPLACE FUNCTION survey_participated(_sn text)
  returns void AS
$func$
BEGIN
  EXECUTE format($$ALTER TABLE participation ADD COLUMN %I integer DEFAULT 0$$,_sn);
  EXECUTE format($$UPDATE TABLE participation SET %I = 1 WHERE participation.participant_id = %I.participant_id$$,_sn,_sn);
END
$func$ LANGUAGE plpgsql;


I keep getting the error:

[2017-10-19 12:38:09] [42601] ERROR: syntax error at or near "TABLE"
[2017-10-19 12:38:09] Where: PL/pgSQL function survey_participated(text) line 4 at EXECUTE


Can someone point out my mistake?
The first problem is the syntax for UPDATE doesn't permit an optional TABLE after. It's just not needed. UPDATE only operates on tables; ALTER works on many targets. The second problem is that should be %s (literal/string) and not %I (identifier).

EXECUTE format(
  $$ALTER TABLE participation ADD COLUMN %I integer DEFAULT 0;$$,
  _sn
);
EXECUTE format(
  $$
    UPDATE participation
    SET %I = 1
    WHERE participation.participant_id = quote_literal(%s||participant_id);
  $$,
  _sn,
  _sn
);


That all said, this seems like a horrible idea. You're adding a column to the table, and setting the value of that column to the "colname+id"? How is that useful?