Create view using postgres function

与世无争的帅哥 提交于 2020-04-30 07:01:05

问题


I'm trying to build a parametrized view using a postgres function:

CREATE FUNCTION schemaB.testFunc(p INT)
RETURNS TABLE 
AS
RETURN (SELECT * FROM schemaZ.mainTable WHERE id=p)

The problem is always the same:

SQL Error [42601]: ERROR: syntax error at or near "AS"

Any idea on what could I be doing wrong?


回答1:


You need to specify the columns of the "return table", this is either done using

returns table(col_1 integer, col_2 text, ...)

In your case you are returning only rows of one table, so it's easier to use

returns setof maintable

As documented in the manual the function body needs to be enclosed in single quotes, or using dollar quoting.

As stored functions can be written in many different languages in Postgres, you also need to specify a language - in this case language sql is suitable.

So putting all that together, you need:

CREATE FUNCTION schemaB.testFunc(p_id INT)
  RETURNS setof  schemaZ.mainTable
AS
$$
 SELECT * 
 FROM schemaZ.mainTable 
 WHERE id = p_id
$$
language sql;

A return statement is not required for language sql functions.



来源:https://stackoverflow.com/questions/61273632/create-view-using-postgres-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!