postgresql - 列引用 "id"不明确 - 它可能引用 PL/pgSQL 变量或表列

标签 postgresql plpgsql

我在 Postgres 中有这个简单的测试函数(在我的 test 模式中)。

CREATE OR REPLACE FUNCTION test.func_001
(
par_id int
)
RETURNS TABLE
(
id int
)

AS
$BODY$
DECLARE

    var_id int;

BEGIN

    update test.item    --- this is a table 
    set 
    id = 4
    WHERE
    id = 44;

return query 
select 1000 as id;

END;
$BODY$
LANGUAGE  plpgsql;

test.item 表有一个 id 列。

我在尝试运行该函数时遇到以下错误。

Query execution failed

Reason:
SQL Error [42702]: ERROR: column reference "id" is ambiguous
  Detail: It could refer to either a PL/pgSQL variable or a table column.
  Where: PL/pgSQL function test.func_001(integer) line 8 at SQL statement

这个错误看起来很奇怪,这是否意味着 Postgres 在 test.item.id 列和返回表中的 id 列之间发现了冲突/冲突? ! 怎么会?这没有任何意义。

我不敢相信,但我在这里没有看到其他 id 用法。

请注意,如果我只注释掉这部分。

-- WHERE
-- id = 44;

然后突然这个功能就可以正常工作了。

所以看起来 Postgres 混淆了 where 中的 id 带有其他名为 id 的子句?!

用什么?

这完全不合逻辑且违反直觉。

谁能解释一下?

最佳答案

子句FUNCTION fx() RETURNS TABLE(x int, y int, ...)FUNCTION(OUT x int, OUT y int) RETURNS SETOF record相同.所以在你的情况下,有隐式变量 id ,尽管您没有明确使用它。

PostgreSQL 设计允许在没有 SQL 的情况下生成行。

CREATE OR REPLACE FUNCTION foo(a int)
RETURNS TABLE(b int, c int) AS $$
BEGIN
  FOR i IN 1..a
  LOOP
    b := i; c := i * 10;
    RETURN NEXT;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

参见 following文件,请。

There is another way to declare a function as returning a set, which is to use the syntax RETURNS TABLE(columns). This is equivalent to using one or more OUT parameters plus marking the function as returning SETOF record (or SETOF a single output parameter's type, as appropriate). This notation is specified in recent versions of the SQL standard, and thus may be more portable than using SETOF.

关于postgresql - 列引用 "id"不明确 - 它可能引用 PL/pgSQL 变量或表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53204855/

相关文章:

postgresql - 使用变量作为 jsonb_extract_path 中的搜索键

arrays - 如何从 Postgres 函数返回新创建的 ids 数组?

postgresql - Postgres PL/pgSQL递归计算

postgresql - 不明确的函数参数

sql - psql: FATAL: 角色连接太多

java - 通过 Java 插入图像时 Postgres 编码 "UTF8"错误

java - 复制到 * CSV 文件时数据不匹配

postgresql - SQLException 太多客户端与身份验证失败

sql - UPDATE ... FROM ... 内部触发函数未按预期工作?

postgresql - 使用 Rails 获取数百个帖子的当前用户投票类型的最佳方法