在Postgres中返回SETOF表的函数

时间:2019-07-03 01:52:11

标签: sql postgresql sql-function quoted-identifier

我正在尝试构建一个满足以下条件的简单函数(需要与Hasura API fwiw link配合使用)

Function behaviour: ONLY STABLE or IMMUTABLE
Return type: MUST be SETOF <table-name>
Argument modes: ONLY IN

这是功能

CREATE FUNCTION fn_sum_views(text) RETURNS SETOF page_analytics AS $$
  SELECT prodID, sum(views) FROM page_analytics WHERE prodID = $1 group by prodID
$$ LANGUAGE SQL STABLE;

我得到错误:"column \"prodid\" does not exist"。当我使用page_analytics.prodID"page_analytics.prodID"\"page_analytics.prodID\"

时,出现相同的错误

1 个答案:

答案 0 :(得分:2)

对于任何包含大写字母的表名或列名,请始终确保使用双引号。否则,它们是converted to lowercase

CREATE FUNCTION fn_sum_views(text) RETURNS SETOF page_analytics AS $$
  SELECT "prodID", sum(views) FROM page_analytics WHERE "prodID" = $1 group by "prodID"
$$ LANGUAGE SQL STABLE;

还请注意,在引用“ page_analytics”时,“ prodID”也将起作用。