Execute dynamic SQL query stored in text variable using Postrgres plpgsql
<p>In the Postgres table named <code>my_table</code>, I want to set all empty strings (<code>''</code>) across all variables to <code>null</code>.  I have the following do-block which fails at the execute line. </p>

<p>I am quite new to <code>plpgsql</code> and do not understand why. 
<strong>How can I properly execute the command stored in <code>q</code>?</strong></p>

<pre><code>do language plpgsql
$$
DECLARE
  r record;
  q text;
BEGIN
   for r in
        select table_name, column_name
        from information_schema.columns t
        where t.table_name = 'my_table'
  loop
    q := format('UPDATE %s SET %s = NULL WHERE %s = '''';',
                    r.table_name, r.column_name, r.column_name);
    raise notice 'cleaning column: %', q;
    execute q;  -- this line fails
   end loop;
END;
$$;
</code></pre>

<p>PS. Any other hints for better code are also welcome :)</p>