自动化分区创建Postgres里10
问题描述:
我试图在由RANGE一个巨大的表自动Postgres里的10个分区(DATE_CREATED)。自动化分区创建Postgres里10
我注意到,没有一个自动创建分区表的,所以我想编写一个程序来自动这些表的创建。
我在想这样的事情:
CREATE OR REPLACE FUNCTION cdi.automating_partitions()
RETURNS TABLE(natural_id text, name text, natural_id_numeric text) AS
$func$
DECLARE
formal_table text;
BEGIN
FOR formal_table IN
select '2017-01-01'::date + (n || ' months')::interval months,
'2013-02-01'::date + (n || ' months')::interval monthsplus
from generate_series(0, 12) n
LOOP
RETURN QUERY EXECUTE
'CREATE TABLE cdi.' || 'document' || to_char(months, 'YYYY') || '' || to_char(months, 'MM') || ' PARTITION OF cdi.document
FOR VALUES FROM (''' || to_char(months, 'YYYY') || to_char(months, 'MM') || ''',
''' to_char(monthsplus, 'YYYY') || to_char(monthsplus, 'MM') ''');'
END LOOP;
END
$func$ LANGUAGE plpgsql;
,但我得到附近(
答
使用与execute
结合功能format()
得到一个清晰可读的代码语法错误,例如:
do $do$
declare
d date;
begin
for d in
select generate_series(date '2017-01-01', date '2017-12-01', interval '1 month')
loop
execute format($f$
create table cdi.document%s%s partition of cdi.document
for values from (%L) to (%L)
$f$,
to_char(d, 'YYYY'), to_char(d, 'MM'), d, d+ interval '1 month');
end loop;
end
$do$
我已经使用了anonymous code block为create table ...
不会产生任何结果。但是,如果想写一个函数,请注意函数应该返回void
而不是使用RETURN QUERY
。
你不能用'execute'一个PL/pgSQL的块之外(和从来没有作为一个SQL查询的一部分) –
你得到什么错误? – JustMe