如何从plpgsql中的循环返回结果?

时间:2016-06-22 09:53:58

标签: postgresql loops plpgsql postgresql-9.4

我希望看到显示日期的结果

 "2001-01-01 00:00:00+05:30"
 "2001-01-02 00:00:00+05:30"
 "2001-01-03 00:00:00+05:30"
 "2001-01-04 00:00:00+05:30"
 "2001-01-05 00:00:00+05:30"
 "2001-01-06 00:00:00+05:30"
 "2001-01-07 00:00:00+05:30"
等等...... 但我得到错误

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 insert_date_dimension(date) line 12 at SQL statement
你可以告诉我这是什么问题

我创建的功能

create or replace function insert_date_dimension("Date" date)
returns text as
$$
Declare dat date;
start_date date;
end_date date;
Begin
start_date:='2016/01/01';
end_date:='2016/12/31';
while start_date<=end_date 
loop
select start_date;
start_date:=start_date+ interval  '1 day';
End loop;
return start_date;
end;
$$
LANGUAGE 'plpgsql';

你能告诉我这个函数有什么问题吗?我无法执行它。我想把所有列都放在选择的陈述中。请告诉我create or replace function insert_date_dimension("date" date) returns setof date as $$ declare dat date; start_date date; end_date date; begin start_date := '2016/01/01'; end_date := '2016/12/31'; while start_date <= end_date loop --return next start_date; select start_date,date_part('week',start_date),date_part('quarter',start_date),to_char(start_date, 'day'),to_char(start_date, 'month'), extract(year from current_date),extract(month from current_date); start_date:= start_date + interval '1 day'; end loop; end; $$ 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 insert_date_dimension(date) line 11 at SQL    statement
  ********** Error **********

1 个答案:

答案 0 :(得分:3)

无需用户定义的功能。只需使用generate_series

select generate_series('2016/01/01'::date, '2016/12/31', '1 day');

但如果您只是在摆弄plpgsql,那么return next setof date

create or replace function insert_date_dimension("date" date)
returns setof date as $$
    declare
        dat date;
        start_date date;
        end_date date;
    begin
        start_date := '2016/01/01';
        end_date := '2016/12/31';
        while start_date <= end_date loop
            return next start_date;
            start_date := start_date + interval  '1 day';
        end loop;
    end;
$$ language plpgsql;

plpgsql是一个标识符。不要引用它。