【问题标题】:Ambiguous column reference - it could refer to either a PL/pgSQL variable or a table column?不明确的列引用 - 它可以引用 PL/pgSQL 变量或表列?
【发布时间】:2021-05-04 12:44:47
【问题描述】:

我在 PostgreSQL 中收到以下错误:

[42702] 错误:列引用“topicid”不明确详细信息:它 可以引用 PL/pgSQL 变量或表列。在哪里: PL/pgSQL function topics(integer) line 3 at RETURN QUERY

我理解这意味着存在同名的参数和表列。除了我看不到它在哪里,因为我唯一的参数是_typeid 而不是topicid

这个函数到底哪里出了问题:

CREATE FUNCTION topics(_typeid integer DEFAULT NULL::integer)
  RETURNS TABLE(topicid integer, typeid integer, topic character varying)
  LANGUAGE plpgsql
AS
$$
BEGIN
RETURN QUERY SELECT
    topicid
     ,typeid
     ,topic
FROM
    topic
WHERE
    _typeid IS NULL
   OR
        typeID = _typeid
ORDER BY
    topic ASC;
END
$$;

如果我将它重构为只使用sql,那么它可以像这样正常工作:

CREATE FUNCTION topics(_typeid integer DEFAULT NULL::integer)
  RETURNS TABLE(topicid integer, typeid integer, topic character varying)
  LANGUAGE sql
AS
$$
SELECT
    topicid
     ,typeid
     ,topic
FROM
    topic
WHERE
    _typeid IS NULL
   OR
        typeID = _typeid
ORDER BY
    topic ASC;
$$;

【问题讨论】:

标签: postgresql plpgsql


【解决方案1】:

RETURNS TABLE 中的变量与查询返回的字段名称之间存在冲突。表限定查询中的字段名称,例如topic.topicid, topic.typid, topic.topic.

【讨论】:

  • 为什么语言通俗sql没有问题?
  • 简短的回答是plpgsql 解析器更严格。更长的答案可以在这里找到Implementation。本节还包括以各种方式覆盖行为的方法。我发现习惯于使列和变量一开始就明确无误会更容易。
猜你喜欢
  • 2014-03-06
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 2023-01-18
  • 2018-08-01
相关资源
最近更新 更多