postgres函数 - 使用select语句声明变量

时间:2016-03-14 14:58:52

标签: postgresql function stored-procedures psql

我修改了我的功能,但是我对声明变量有问题。我使用了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 

_minid := (SELECT id from tablename  where starttime >= $1 ORDER BY tablename2 ASC LIMIT 1); 
_maxid := (SELECT id from tablename  where starttime < $2 ORDER BY tablename2 DESC LIMIT 1); 

SELECT CASE WHEN duration <= 10000000 THEN '00-01 sec'::text
            WHEN duration <= 40000000 THEN '01-04 sec'
            WHEN duration <= 100000000 THEN '04-10 sec' 
            WHEN duration <= 300000000 THEN '10-30 sec' 
            WHEN duration <= 600000000 THEN '30-60 sec' 
            ELSE 'more than 60 sec' END  
     , count(*)::int                     
FROM   tablename
WHERE  id >= _minid and id <= _maxid
GROUP  BY 1                              
ORDER  BY 1; 

END; 
$func$ LANGUAGE plpgsql; 

错误:

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 11 at SQL statement

Regrads

1 个答案:

答案 0 :(得分:0)

现在有效:

   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 < $2 ORDER BY starttime DESC LIMIT 1; 

    Return Query SELECT CASE WHEN duration <= 10000000 THEN '00-01 sec'::text
                WHEN duration <= 40000000 THEN '01-04 sec'
                WHEN duration <= 100000000 THEN '04-10 sec' 
                WHEN duration <= 300000000 THEN '10-30 sec' 
                WHEN duration <= 600000000 THEN '30-60 sec' 
                ELSE 'more than 60 sec' END  
         , count(*)::int                     
    FROM   tablename
    WHERE  id >= _minid and id <= _maxid
    GROUP  BY 1                              
    ORDER  BY 1; 

    END; 
    $func$ LANGUAGE plpgsql;