title: How to create a trigger function dynamically in pgsql?
body: <p>I want to write a pgsql function to create trigger dynamically. For example, a trigger to count insertions in each table. I've tried EXECUTE like this:</p>
  
  <pre><code>CREATE FUNCTION trigen(tbl text) RETURNS void AS $$
  BEGIN
      EXECUTE format(
      'CREATE FUNCTION %s_insertCnt() RETURNS TRIGGER AS $$
      BEGIN
          UPDATE insertions SET n = n + 1 WHERE tablename = %s;
      END
      $$ LANGUAGE plpgsql', tbl, quote_nullable(tbl));
  
      EXECUTE format('CREATE TRIGGER %s_inCnt BEFORE INSERT ON %s
      FOR EACH ROW EXECUTE PROCEDURE %s_insertCnt();', tbl, tbl, tbl);
  END
  $$ LANGUAGE plpgsql
  </code></pre>
  
  <p>But this approach doesn't work. A lot of syntax error occurred when I import this code. It seems that EXECUTE cannot execute a function creation.</p>
  
  <p>What else can I do to create trigger functions dynamically?</p>