我正在尝试将循环中的值插入到表中但由于我的函数抛出错误而无法执行此操作..
我想将从select statment获取的数据插入基表Date_Dim。
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
insert into date_dim
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;$$;
ERROR: cannot open INSERT query as cursor
CONTEXT: PL/pgSQL function insert_date_dimension() line 6 at RETURN QUERY
答案 0 :(得分:0)
我认为这不是选择查询。所以返回值应该像那样
RETURNS VOID
而不是
RETURN QUERY
您还需要将IN替换为IN参数
答案 1 :(得分:0)
如果要返回刚刚插入的行,则需要使用returning
您还可以使用returns setof date_dim
:
CREATE OR REPLACE FUNCTION insert_date_dimension()
RETURNS SETOF date_dim
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
insert into date_dim
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)
returning *; --<< HERE
END;
$$
;