2017-10-17 145 views
1

我试图在由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; 

,但我得到附近(

+2

你不能用'execute'一个PL/pgSQL的块之外(和从来没有作为一个SQL查询的一部分) –

+1

你得到什么错误? – JustMe

回答

1

使用与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 blockcreate table ...不会产生任何结果。但是,如果想写一个函数,请注意函数应该返回void而不是使用RETURN QUERY