如何在Postgres中使用DO [英] How to use DO in postgres

查看:355
本文介绍了如何在Postgres中使用DO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图更好地理解PostgreSQL 9.1中的 DO 命令

I am attempting to get a better understanding of the DO command in postgreSQL 9.1

我有以下代码

DO
$do$
BEGIN
IF 1=1 THEN
SELECT 'foo';
ELSE
SELECT 'bar';
END IF;
END
$do$

但是它返回以下错误:

[42601]错误:查询没有结果数据的目的地提示:如果要舍弃SELECT的结果,请改用PERFORM。其中:PL / pgSQL函数 inline_code_block在SQL语句的第4行

[42601] ERROR: query has no destination for result data Hint: If you want to discard the results of a SELECT, use PERFORM instead. Where: PL/pgSQL function "inline_code_block" line 4 at SQL statement

推荐答案

PostgreSQL DO 命令创建并执行一些特定的短寿命函数。此函数没有任何接口,因此它不能返回任何输出,只能更改表中的数据和某些调试输出。

PostgreSQL DO command creates and executes some specific short life function. This function has not any interface, and then it cannot to return any output other then changes data in tables and some debug output.

您的示例有多个问题:


  1. 仅PostgreSQL表函数可以返回一些表格数据。但是该机制与MSSQL明显不同。 PostgreSQL用户应该使用返回下一个返回查询命令。

CREATE OR REPLACE FUNCTION foo(a int)
RETURNS TABLE(b int, c int) AS $$
BEGIN
  RETURN QUERY SELECT i, i + 1 FROM generate_series(1,a) g(i);
END;
$$ LANGUAGE plpgsql;

SELECT * FROM foo(10);


  • DO 匿名函数不是表函数-因此不允许输出。

  • DO anonymous functions are not table functions - so no output is allowed.

    不支持PostgreSQL 9.1版本,请升级

    PostgreSQL 9.1 is not supported version, please upgrade

    如果您仅具有MSSQL的经验,那就算了。 PostgreSQL的存储过程概念与Oracle或DB2非常相似,并且与MSSQL显着不同。 T-SQL将过程和SQL构造集成到一组。 Oracle,PostgreSQL,...过程功能可以嵌入SQL,但是过程功能未集成到SQL。

    If you have some experience only from MSSQL, then forget it. A concept of stored procedures of PostgreSQL is very similar to Oracle or DB2, and it is significantly different to MSSQL does. T-SQL integrates procedural and SQL constructs to one set. Oracle, PostgreSQL, ... procedural functionality can embedded SQL, but procedural functionality is not integrated to SQL.

    请阅读PostgreSQL PLpgSQL 文档,以更好地了解该技术。

    Please, read PostgreSQL PLpgSQL documentation for better imagine about this technology.

    这篇关于如何在Postgres中使用DO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆