Search code examples
postgresqlplpgsql

Postgres execute dynamic anonymous block in an anonymous block


How could I execute in PostgreSQL pl/pgSQL an anonymous block from a string? There is execute, but it doesn't seem to accept a begin-end block as command-string (or I couldn't figure out how)

do $$
declare
  myBlock := 'begin null; end;';
begin
  execute myBlock;
end;
$$

ERROR:  syntax error at or near "null"
LINE 1: begin null; end;
              ^
QUERY:  begin null; end;
CONTEXT:  PL/pgSQL function inline_code_block line 5 at EXECUTE
SQL state: 42601

And there is do, but it only accepts a string literal, no variables (and thus doesn't feel very useful inside a pgsql block...)

do $$
begin
  do 'begin null; end;';
end;
$$

But the code block to be executed is fetched from a table, thus do won't do.


Solution

  • You need to run another DO block in the dynamic SQL string:

    do $$
    declare
      myBlock text := 'do $nested$ begin raise notice $m$Hello$m$; end; $nested$';
    begin
      execute myBlock;
    end;
    $$