2017-10-17 142 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