Why PostgreSQL need script for Execute and not need script for query_to_xml?

大憨熊 提交于 2021-02-11 14:10:46

问题


I am new to PostgreSQL. I have a doubt about PostgreSQL script .

In my last question i was trying to use "execute" . Then i come to know , If i want to use Execute in query i have to make script (use $$ LANGUAGE ... ).

But one answer from similar questions , use query_to_xml and it not need script . why ?


回答1:


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.



来源:https://stackoverflow.com/questions/49281340/why-postgresql-need-script-for-execute-and-not-need-script-for-query-to-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!