我有从命令行运行的以下(工作)代码:

DO $$
DECLARE first_ext INTEGER;
        last_ext INTEGER;
BEGIN
   first_ext:=100;
   last_ext:=150;

   INSERT INTO widgets (username)
   SELECT i
   FROM generate_series(first_ext, last_ext) AS t(i);

   INSERT INTO widget2
   SELECT generate_series(first_ext, last_ext), 'sometext',
          generate_series(first_ext, last_ext);
END $$;

我现在要对这两个表进行计数,以确保正确创建了数据。
但我很难回值。我就是这么想的:
RETURNS rec_count AS
DO $$
DECLARE first_ext INTEGER;
        last_ext INTEGER;
BEGIN
   first_ext:=100;
   last_ext:=150;

   INSERT INTO widgets (username)
   SELECT i
   FROM generate_series(first_ext, last_ext) AS t(i);

   INSERT INTO widget2
   SELECT generate_series(first_ext, last_ext), 'sometext',
          generate_series(first_ext, last_ext);

   SELECT COUNT(*) FROM widget2 INTO rec_count;
END $$;

但它失败了,错误如下:
ERROR:  syntax error at or near "RETURNS" LINE 1: RETURNS rec_count AS

我不想把它变成一个函数/存储过程。
还有别的办法吗?

最佳答案

不能从DO语句返回值。有多种解决方法:
Get result from query in DO satement
但为什么不创建一个临时函数呢?

CREATE FUNCTION pg_temp.f_dummy(OUT rec_count bigint) AS
$func$
DECLARE
   first_ext int := 100;  -- assign at declaration time
   last_ext  int := 150;
BEGIN
   INSERT INTO widgets (username)
   SELECT i
   FROM   generate_series(first_ext, last_ext) i;

   INSERT INTO widget2(col_a, col_b, col_c)  -- column names !?
   SELECT i, 'sometext', i
   FROM   generate_series(first_ext, last_ext) i;  -- do not call it twice

   SELECT COUNT(*) FROM widget2 INTO rec_count;  -- counts *all* rows in widget2
END
$func$  LANGUAGE plpgsql;

呼叫:
SELECT pg_temp.f_dummy();

仅在当前会话中可见;与所有临时对象一样在会话结束时终止。
How to create a temporary function in PostgreSQL?
或者只使用一个SQL语句来修改CTE和RETURNING子句:
WITH ins1 AS (
   INSERT INTO widgets (username)
   SELECT i
   FROM   generate_series(100, 150) i  --  enter number here *once*
   RETURNING username
   )
, ins2 AS (
   INSERT INTO widget2(username, txt, some_int)
   SELECT username, 'sometext', username
   FROM   ins1
   RETURNING widget2.username
   )
SELECT count(*) FROM ins2;

只计算widget2中新插入的行,不包括预先存在的行。
旁白:usernameinteger列的奇数列名。

关于postgresql - 如何从使用匿名DO的.sql文件返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41308248/

10-15 18:45