[英]Why PostgreSQL need script for Execute and not need script for query_to_xml?
I am new to PostgreSQL. 我是PostgreSQL的新手。 I have a doubt about PostgreSQL script .
我对PostgreSQL脚本有疑问。
In my last question i was trying to use "execute" . 在我的最后一个问题中,我试图使用“ execute”。 Then i come to know , If i want to use Execute in query i have to make script (use $$ LANGUAGE ... ).
然后我知道,如果我想在查询中使用执行,我必须制作脚本(使用$$ LANGUAGE ...)。
But one answer from similar questions , use query_to_xml and it not need script . 但是,对于类似问题的一个答案是,使用query_to_xml,它不需要脚本。 why ?
为什么呢?
Unlike SQL Server, Postgres (and many other DBMS like Oracle, DB2, Firebird) makes a clear distinct between procedural code and SQL. 与SQL Server不同,Postgres(以及许多其他DBMS,例如Oracle,DB2,Firebird)在过程代码和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. do
块本质上是一个不返回任何内容的匿名函数。
Dynamic SQL can only be used in procedural code. 动态SQL只能在过程代码中使用。
query_to_xml
does exactly that: it uses dynamic SQL. query_to_xml
正是这样做的:它使用动态SQL。
To count the rows in a table you could also create a function that uses dynamic SQL: 要计算表中的行,您还可以创建一个使用动态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. query_to_xml
与count_rows()
函数实质上具有相同的功能-它只是运行任何 SQL语句并将结果返回为XML的通用函数,而不是仅执行一件事的专用函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.