postgresql – 它可以引用一个PL / pgSQL变量或一个表列

前端之家收集整理的这篇文章主要介绍了postgresql – 它可以引用一个PL / pgSQL变量或一个表列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在pgsql中有一个函数
CREATE OR REPLACE FUNCTION core.date_bs_from_ad(date_in_ad date)
  RETURNS character varying AS
$$
BEGIN
    RETURN(
        SELECT date_in_bs FROM core.date_conversion
        WHERE date_in_ad = $1
    );
END
$$

  LANGUAGE plpgsql;

它创建没有错误,但是当我使用这个功能它通过以下错误

ERROR:  column reference "date_in_ad" is ambiguous
LINE 3:   WHERE date_in_ad = $1
                ^
DETAIL:  It could refer to either a PL/pgsql variable or a table column.
QUERY:  SELECT (
        SELECT MAX(date_in_bs) FROM core.date_conversion
        WHERE date_in_ad = $1
    )
CONTEXT:  PL/pgsql function core.date_bs_from_ad(date) line 3 at RETURN
********** Error **********

ERROR: column reference "date_in_ad" is ambiguous
sql state: 42702
Detail: It could refer to either a PL/pgsql variable or a table column.
Context: PL/pgsql function core.date_bs_from_ad(date) line 3 at RETURN
sql标识符和Plpgsql变量之间存在冲突.没有干净,你想要什么你写了一个谓词,总是真的.

好用:

>前缀(通常为“_”)用于局部变量
>嵌入式sql中的限定名称 – 如table_name.column_name

所以这两种技术(只有一个是必要的)

CREATE OR REPLACE FUNCTION core.date_bs_from_ad(_date_in_ad date)
RETURNS character varying AS $$
BEGIN
  RETURN SELECT dc.date_in_bs
             FROM core.date_conversion dc
            WHERE dc.date_in_ad = _date_in_ad;
END
$$ LANGUAGE plpgsql;

对于这些一行函数,sql语言更好:

CREATE OR REPLACE FUNCTION core.date_bs_from_ad(_date_in_ad date)
RETURNS character varying AS $$
   SELECT dc.date_in_bs
      FROM core.date_conversion dc
     WHERE dc.date_in_ad = $1; 
$$ LANGUAGE sql;
原文链接:/postgresql/191746.html

猜你在找的Postgre SQL相关文章