Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

postgresql - plpgsql function returns table(..)

I'm trying to get this plpgsql function to work:

CREATE OR REPLACE FUNCTION outofdate(actualdate varchar) 
RETURNS TABLE(designacion varchar(255),timebeingrotten varchar(255))
AS $BODY$

 SELECT designacao, actualdate - prazo
 FROM alimento
 WHERE prazo < actualdate;
$BODY$ 
LANGUAGE 'plpgsql' volatile;

SELECT *
From outofdate('12/12/2012');

It keeps giving me an error on line 2 - table ..

ERROR: syntax error at or near "TABLE" LINE 2: RETURNS TABLE(designacion varchar(255),timebeingrotten varch... ^

*** Error ***

ERROR: syntax error at or near "TABLE" SQL state: 42601 Character: 67

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am not sure, but maybe you use a older version of pg without support of RETURNS TABLE syntax. Next problem in your example is wrong syntax for PL/pgSQL language - look to manual for syntax - every function must contain a block with BEGIN ... END. Records can be returned via RETURN QUERY statement. Have a look at this tutorial.

CREATE OR REPLACE FUNCTION foo(a int)
RETURNS TABLE(b int, c int) AS $$
BEGIN
  RETURN QUERY SELECT i, i+1 FROM generate_series(1, a) g(i);
END;
$$ LANGUAGE plpgsql;

Call:

SELECT * FROM foo(10);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...