Unlike SQL Server, Postgres (and many other DBMS like Oracle, DB2, Firebird) makes a clear distinct between procedural code and SQL. Procedural code can only be run in the context of a function (or procedure). A do
block is essentially an anonymous function that doesn't return anything.
Dynamic SQL can only be used in procedural code. query_to_xml
does exactly that: it uses dynamic SQL.
To count the rows in a table you could also create a function that uses dynamic SQL:
create function count_rows(p_schemaname text, p_tablename text)
returns bigint
as
$$
declare
l_stmt text;
l_count bigint;
begin
l_stmt := format('select count(*) from %I.%I', p_schemaname, p_tablename);
execute l_stmt
into l_count;
return l_count;
end;
$$
language plpgsql;
You can then use:
select schema_name, table_name, count_rows(schema_name, table_name)
from information_schema.tables
where schema_name = 'public';
query_to_xml
does essentially the same thing as the function count_rows()
- it's just a generic function to run any SQL statement and return that result as XML, rather than a specialized function that only does exactly one thing.