Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 310
David Dias Avatar asked Nov 25 '10 18:11

David Dias


People also ask

Can a PostgreSQL function return a table?

PostgreSQL returns a table with one column that holds the array of films. In practice, you often process each individual row before appending it in the function's result set. The following example illustrates the idea.

What is Plpgsql function?

With PL/pgSQL you can group a block of computation and a series of SQL queries inside the database server, thus having the power of a procedural language and the ease of use of SQL. Also, with PL/pgSQL you can use all the data types, operators and functions of Greenplum Database SQL.

How do I return a set of records in PostgreSQL?

Let's make a function that returns all the rows of a table whose name you pass in as a parameter. create or replace function GetRows(text) returns setof record as ' declare r record; begin for r in EXECUTE ''select * from '' || $1 loop return next r; end loop; return; end ' language 'plpgsql';


1 Answers

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);
like image 87
Pavel Stehule Avatar answered Sep 28 '22 06:09

Pavel Stehule