简单的postgres功能

时间:2018-06-07 16:24:36

标签: postgresql

我尝试在postgres中声明简单的函数,但我无法使它工作。它看起来像这样:

CREATE OR REPLACE FUNCTION test2(rok int, id int)
  RETURNS int AS $$
BEGIN
select sum(data_zakonczenia-data_rozpoczecia) from historia where id_eksponatu = $2 AND data_rozpoczecia>DATE(to_char($1,'9999') || '-01-01') AND data_zakonczenia<DATE(to_char($1+1,'9999') || '-01-01');
END;
$$ LANGUAGE 'plpgsql';

我收到以下错误

ERROR:  query has no destination for result data
PODPOWIEDŹ:  If you want to discard the results of a SELECT, use PERFORM instead.
KONTEKST:  PL/pgSQL function "test2" line 2 at SQL statement

我不确定如何使其发挥作用。

3 个答案:

答案 0 :(得分:2)

你想要一个SQL函数:

CREATE OR REPLACE FUNCTION test2(rok int, id int)
  RETURNS int AS 
$$
   select sum(data_zakonczenia-data_rozpoczecia) 
   from historia where id_eksponatu = $2 
    AND data_rozpoczecia>DATE(to_char($1,'9999') || '-01-01') 
    AND data_zakonczenia<DATE(to_char($1+1,'9999') || '-01-01');
$$ LANGUAGE sql;

或者如果出于某种原因需要PL / pgSQL,则需要使用return query

CREATE OR REPLACE FUNCTION test2(rok int, id int)
  RETURNS int AS $$
BEGIN
  return query
    select sum(data_zakonczenia-data_rozpoczecia) 
    from historia where id_eksponatu = $2 
     AND data_rozpoczecia>DATE(to_char($1,'9999') || '-01-01') 
     AND data_zakonczenia<DATE(to_char($1+1,'9999') || '-01-01');
END;
$$ LANGUAGE plpgsql;

或者如果您在返回之前需要对值执行某些操作:

CREATE OR REPLACE FUNCTION test2(rok int, id int)
  RETURNS int AS $$
declare 
   l_sum integer;
BEGIN
  select sum(data_zakonczenia-data_rozpoczecia) 
      into l_sum
  from historia where id_eksponatu = $2 
   AND data_rozpoczecia>DATE(to_char($1,'9999') || '-01-01') 
   AND data_zakonczenia<DATE(to_char($1+1,'9999') || '-01-01');

   ....

  return l_sum;         
END;
$$ LANGUAGE plpgsql;

语言名称是标识符。不要把它放在单引号中。

答案 1 :(得分:0)

好的,按照我的评论提示:

CREATE OR REPLACE FUNCTION test2(rok int, id int)
  RETURNS int AS $$
DECLARE
suma int;
BEGIN
select sum(data_zakonczenia-data_rozpoczecia) into suma from historia where id_eksponatu = $2 AND data_rozpoczecia>DATE(to_char($1,'9999') || '-01-01') AND data_zakonczenia<DATE(to_char($1+1,'9999') || '-01-01');
return suma;
END;
$$ LANGUAGE 'plpgsql';

答案 2 :(得分:0)

RETURN (select sum(data_zakonczenia-data_rozpoczecia) from historia where id_eksponatu = $2 AND data_rozpoczecia>DATE(to_char($1,'9999') || '-01-01') AND data_zakonczenia<DATE(to_char($1+1,'9999') || '-01-01'));

编辑:您已使用“return”语句。我想另一个答案建议你可以使用“返回查询”,如果你想返回一个表而不是一个整数。