HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Declare variable for SELECT statement in Postgres function

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresstatementfunctiondeclareforselectvariable

Problem

I have modified my function, but I have problems with declaring variables. I use Postgres 8.4.

CREATE OR REPLACE FUNCTION requestcounterid(_mindate timestamptz, _maxdate timestamptz) 
  RETURNS TABLE (kategorien text, requestcounter int) AS
$func$  
DECLARE
_minid bigint;
_maxid bigint;

BEGIN 

SELECT id  INTO _minid from tablename
where starttime >= $1 ORDER BY starttime ASC LIMIT 1; 
SELECT id  INTO _maxid from tablename
where starttime = _minid and id <= _maxid
GROUP  BY 1                              
ORDER  BY 1; 

END; 
$func$ LANGUAGE plpgsql;


Error:

ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT:  PL/pgSQL function "requestcounterid" line 12 at SQL statement


How to fix this?

Solution

If the SELECT with the CASE expression is something you want to return in the output table, just add RETURN QUERY before it:

RETURN QUERY SELECT CASE ...


Note: 8.4 is very old now. Even 9.0 is out of support by now - consider upgrading to a recent major version soon. The old ones usually don't get any security (and other) fixes anymore.

Code Snippets

RETURN QUERY SELECT CASE ...

Context

StackExchange Database Administrators Q#132268, answer score: 4

Revisions (0)

No revisions yet.