用户定义函数返回PostgreSQL中的表

时间:2014-02-16 00:26:36

标签: sql postgresql user-defined-functions

我正在尝试创建一个返回包含四个值的表的UDF:

CREATE TABLE ts_table
(
  id character varying, 
  year integer, 
  rank double precision, 
  votes integer
);

然后,使用UDF,我必须返回一个由(某些东西)定义的表:

CREATE FUNCTION ts_myfunc(text) RETURNS SETOF ts_table AS $$
    'SELECT id,year,rank,votes FROM productions NATURAL JOIN directors NATURAL JOIN ratings WHERE attr is NULL AND pid=$1 ORDER BY year;'
$$ LANGUAGE SQL;

但是,当我尝试使用该命令创建UDF时,我得到了

ERROR:  syntax error at or near "'SELECT id,year,rank,votes FROM productions NATURAL JOIN directors NATURAL JOIN ratings WHERE attr is NULL AND pid=$1 ORDER BY year;'"
LINE 2: 'SELECT id,year,rank,votes FROM productions NATURAL JOIN dir...

1 个答案:

答案 0 :(得分:0)

更改线路 'SELECT id,year,rank,votes FROM productions NATURAL JOIN directors NATURAL JOIN ratings WHERE attr is NULL AND pid=$1 ORDER BY year;'

SELECT id,year,rank,votes FROM productions NATURAL JOIN directors NATURAL JOIN ratings WHERE attr is NULL AND pid=$1 ORDER BY year;

(删除单引号)将解决问题。