简体   繁体   English

如何在Postgres中使用DO

[英]How to use DO in postgres

I am attempting to get a better understanding of the DO command in postgreSQL 9.1 我试图更好地了解PostgreSQL 9.1中的DO命令

I have following code block, 我有以下代码块,

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

However it returns the following error: 但是,它返回以下错误:

[42601] ERROR: query has no destination for result data Hint: If you want to discard the results of a SELECT, use PERFORM instead. [42601]错误:查询没有结果数据的目的地提示:如果要舍弃SELECT的结果,请改用PERFORM。 Where: PL/pgSQL function "inline_code_block" line 4 at SQL statement 其中:SQL语句中的PL / pgSQL函数“ inline_code_block”第4行

PostgreSQL DO command creates and executes some specific short life function. PostgreSQL DO命令创建并执行一些特定的短寿命函数。 This function has not any interface, and then it cannot to return any output other then changes data in tables and some debug output. 此函数没有任何接口,因此它不能返回任何输出,只能更改表中的数据和某些调试输出。

Your example has more than one issues: 您的示例有多个问题:

  1. Only PostgreSQL table functions can returns some tabular data. 只有PostgreSQL表函数可以返回一些表格数据。 But the mechanism is significantly different than MSSQL. 但是该机制与MSSQL明显不同。 PostgreSQL user's should to use RETURN NEXT or RETURN QUERY commands. PostgreSQL用户应使用RETURN NEXTRETURN QUERY命令。

     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); 
  2. DO anonymous functions are not table functions - so no output is allowed. DO匿名函数不是表函数-因此不允许输出。

  3. PostgreSQL 9.1 is not supported version, please upgrade 不支持PostgreSQL 9.1版本,请升级

If you have some experience only from MSSQL, then forget it. 如果您仅具有MSSQL的经验,那就算了。 A concept of stored procedures of PostgreSQL is very similar to Oracle or DB2, and it is significantly different to MSSQL does. PostgreSQL的存储过程概念与Oracle或DB2非常相似,并且与MSSQL显着不同。 T-SQL integrates procedural and SQL constructs to one set. T-SQL将过程和SQL构造集成到一组。 Oracle, PostgreSQL, ... procedural functionality can embedded SQL, but procedural functionality is not integrated to SQL. Oracle,PostgreSQL,...过程功能可以嵌入SQL,但是过程功能未集成到SQL。

Please, read PostgreSQL PLpgSQL documentation for better imagine about this technology. 请阅读PostgreSQL PLpgSQL 文档,以更好地了解该技术。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM