postgresql 使用 exec 而不是 select 调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18315633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:22:15  来源:igfitidea点击:

Calling functions with exec instead of select

postgresqlpsql

提问by Diego

Is the default way of calling a function select * from my_function()?

是调用函数的默认方式select * from my_function()吗?

I ask because I have built a function that doesn't return anything, just inserts data into a table and (coming from a SQL Server background) it "feels" strange to call it with select * from...

我问是因为我构建了一个不返回任何内容的函数,只是将数据插入表中,并且(来自 SQL Server 背景)调用它“感觉”很奇怪 select * from...

I was expecting something like exec my_function()

我期待着类似的东西 exec my_function()

回答by Roman Pekar

use PERFORMstatement - http://www.postgresql.org/docs/current/static/plpgsql-statements.html

使用PERFORM语句 - http://www.postgresql.org/docs/current/static/plpgsql-statements.html

Sometimes it is useful to evaluate an expression or SELECT query but discard the result, for example when calling a function that has side-effects but no useful result value. To do this in PL/pgSQL, use the PERFORM statement

有时,评估表达式或 SELECT 查询但丢弃结果很有用,例如在调用具有副作用但没有有用结果值的函数时。要在 PL/pgSQL 中执行此操作,请使用 PERFORM 语句

so it's just

所以这只是

DO $$ BEGIN
    PERFORM my_function();
END $$;

回答by Craig Ringer

PostgreSQL 11:

PostgreSQL 11:

PostgreSQL 11 supports true stored proceduresas pointed out by @AbdisamadKhalif . They support in-procedure transaction control.

正如@AbdisamadKhalif 所指出的那样,PostgreSQL 11支持真正的存储过程。它们支持过程中事务控制。

Older versions:

旧版本:

Yes, that's the standard way, and yes it's weird.

是的,这是标准方式,是的,这很奇怪。

Usually you'd write such functions as stored proceduresand invoke them with the CALLor EXECUTEcommand. PostgreSQL does not support true stored procedures (multiple result sets, autonomous transactions, and all that) though, only sql-callable user-defined functions.

通常您会编写诸如存储过程之类的函数并使用CALLorEXECUTE命令调用它们。PostgreSQL 不支持真正的存储过程(多个结果集、自治事务等),但只支持sql 可调用的用户定义函数

So the workaround is to SELECT function_name()using the PostgreSQL extension syntax that omits FROM, or SELECT 1 FROM function_name();to be (somewhat) more standard.

因此,解决方法是SELECT function_name()使用省略 的 PostgreSQL 扩展语法FROM,或者SELECT 1 FROM function_name();(有点)更标准。

The ODBC driver, JDBC driver, etc understand the {call func_name()}escape syntax and automatically translate it to an underlying SELECT.

ODBC 驱动程序、JDBC 驱动程序等理解{call func_name()}转义语法并自动将其转换为底层SELECT.

回答by Clodoaldo Neto

You will use fromwhen the function returns a set. If the function returns voidjust do

from当函数返回一个集合时,您将使用。如果函数返回void就做

select my_function();