未终止的美元引号字符串创建 PostgreSQL 函数

Unterminated dollar-quoted string creating PostgreSQL function

使用 PostgreSQL 12.3,我在尝试验证这个简单的 plpgsql 代码块时遇到了一些问题

create or replace function test() 
returns void 
as $$
begin
  prepare plan as select 1;
  execute plan;
end;
$$ language plpgsql;

错误是

Unterminated dollar-quoted string at or near "$$ begin prepare plan as select 1;"

我在 end 之后尝试过使用和不使用 ;。我也尝试过使用 sql 而不是 plpgsql。 知道哪里出了问题吗?

这是一个db-fiddle快速测试代码:

https://www.db-fiddle.com/f/KgRZcxXqJs2Lwe284Mj5y/3

问题不在于 $$ 引用:

create or replace function test() 
returns void 
as $$
begin
  prepare plan as select 1;
  execute plan;
end;
$$ language plpgsql;
CREATE FUNCTION

 select test();
ERROR:  column "plan" does not exist
LINE 1: SELECT plan
               ^
QUERY:  SELECT plan
CONTEXT:  PL/pgSQL function test() line 4 at EXECUTE

当你在 dbfiddle 中 运行 时,完整的错误输出是:

 Schema Error: error: unterminated dollar-quoted string at or near "$$ begin prepare plan as select 1;"
Schema Error: error: prepared statement "plan" does not exist
Schema Error: error: unterminated dollar-quoted string at or near "$$ language plpgsql;"
Query Error: error: function test() does not exist 

问题是 EXECUTE inside plpgsql 是它自己的命令:

https://www.postgresql.org/docs/12/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

EXECUTE command-string [ INTO [STRICT] target ] [ USING expression [, ... ] ];

我会使用 plpgsql 表单。这有效:

create or replace function test() 
returns void 
as $$
begin
  prepare plan as select 1;
  EXECUTE 'execute plan';
  RAISE NOTICE 'Made it';
  DEALLOCATE plan;
end;
$$ language plpgsql;

select test();
NOTICE:  Made it
 test 
------
 
(1 row)