Pl/pgSQL anonymous code block fails on [42601] ERROR: query has no destination for result data
Pl/pgSQL anonymous code block fails on [42601] ERROR: query has no destination for result data
假设下面的简化 DO
匿名代码块位于我在应用程序启动时导入的 sql
脚本中:
-- table definitions omitted
-- assume I want to use anonymous code because of looping
DO
$$
DECLARE
parentId BIGINT;
inputArray VARCHAR[][] := ARRAY [['a', 'A'], ['b', 'B'], ['c', 'C']];
input VARCHAR[];
BEGIN
FOREACH input SLICE 1 IN ARRAY inputArray
LOOP
INSERT INTO myParent (name) VALUES (input[1]) RETURNING id AS parentId;
INSERT INTO myTable (id, name) VALUES (parentId, input[2]);
END LOOP;
END;
$$ LANGUAGE plpgsql;
导入并执行脚本后,由于以下错误而失败:
[42601] ERROR: query has no destination for result data
Where: PL/pgSQL function inline_code_block line 13 at SQL statement
我在 https://www.postgresql.org/docs/current/sql-do.html 阅读了 PostgreSQL DO
语句文档,它说:
DO executes an anonymous code block, or in other words a transient anonymous function in a procedural language.
The code block is treated as though it were the body of a function with no parameters, returning void. It is parsed and executed a single time.
我希望 DO
匿名代码中的 INSERT
语句能够顺利执行并继续。如前所述,它是一个没有参数并返回 void 的函数。为什么它是预期的结果数据和存储它们的东西?
我发现 RETURNING
导致了问题并混淆了整个块的 return 类型。 AS
应该替换为 INTO
然后块开始完美地工作。
- 错误:
INSERT INTO myParent (name) VALUES (input[1]) RETURNING id AS parentId;
- 正确:
INSERT INTO myParent (name) VALUES (input[1]) RETURNING id INTO parentId;
假设下面的简化 DO
匿名代码块位于我在应用程序启动时导入的 sql
脚本中:
-- table definitions omitted
-- assume I want to use anonymous code because of looping
DO
$$
DECLARE
parentId BIGINT;
inputArray VARCHAR[][] := ARRAY [['a', 'A'], ['b', 'B'], ['c', 'C']];
input VARCHAR[];
BEGIN
FOREACH input SLICE 1 IN ARRAY inputArray
LOOP
INSERT INTO myParent (name) VALUES (input[1]) RETURNING id AS parentId;
INSERT INTO myTable (id, name) VALUES (parentId, input[2]);
END LOOP;
END;
$$ LANGUAGE plpgsql;
导入并执行脚本后,由于以下错误而失败:
[42601] ERROR: query has no destination for result data Where: PL/pgSQL function inline_code_block line 13 at SQL statement
我在 https://www.postgresql.org/docs/current/sql-do.html 阅读了 PostgreSQL DO
语句文档,它说:
DO executes an anonymous code block, or in other words a transient anonymous function in a procedural language.
The code block is treated as though it were the body of a function with no parameters, returning void. It is parsed and executed a single time.
我希望 DO
匿名代码中的 INSERT
语句能够顺利执行并继续。如前所述,它是一个没有参数并返回 void 的函数。为什么它是预期的结果数据和存储它们的东西?
我发现 RETURNING
导致了问题并混淆了整个块的 return 类型。 AS
应该替换为 INTO
然后块开始完美地工作。
- 错误:
INSERT INTO myParent (name) VALUES (input[1]) RETURNING id AS parentId;
- 正确:
INSERT INTO myParent (name) VALUES (input[1]) RETURNING id INTO parentId;