请告诉我如何执行此操作我想在循环时选择多个列..
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 "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)" returned 7 columns
CONTEXT:PL / pgSQL函数insert_date_dimension(date)第11行在RETURN NEXT
答案 0 :(得分:0)
发生错误是因为您必须在PL / pgSQL函数中使用SELECT ... INTO ...
。此外,你忘了RETURN
某事。
使用generate_series
要容易得多;这样你甚至可能不需要定义一个函数,你可以使用INSERT INTO ... SELECT ...
。
这是我写的功能:
CREATE OR REPLACE FUNCTION insert_date_dimension(
OUT "date" date,
OUT week integer,
OUT quarter integer,
OUT dayname text,
OUT monthname text,
OUT year integer,
OUT month integer
) RETURNS SETOF RECORD STABLE LANGUAGE plpgsql AS
$$DECLARE
dat date;
start_date timestamp := '2016-01-01 00:00:00';
end_date timestamp := '2016-12-31 00:00:00';
BEGIN
RETURN QUERY SELECT
d::date,
date_part('week', d)::integer,
date_part('quarter', d)::integer,
to_char(d, 'day'),
to_char(d, 'month'),
date_part('year', d)::integer,
date_part('month', d)::integer
FROM generate_series(start_date, end_date, '1 day') d(d);
END;$$;