我在 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/