Re: how to prepare a create table statement

From: Pavel Stehule <pavel(dot)stehule(at)gmail(dot)com>
To: Alexander Mills <alexander(dot)d(dot)mills(at)gmail(dot)com>
Cc: PostgreSQL mailing lists <pgsql-bugs(at)lists(dot)postgresql(dot)org>
Subject: Re: how to prepare a create table statement
Date: 2021-01-04 10:51:03
Message-ID: CAFj8pRAr69=V+Fq_zFipsz_jVQ-3LHXeXRbM_Tex2yG_62QQDg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

po 4. 1. 2021 v 11:31 odesílatel Alexander Mills <
alexander(dot)d(dot)mills(at)gmail(dot)com> napsal:

> I am trying to create 500 partitions using a loop:
>
> do $$
> declare
> counter integer := 0;
> begin
> while counter <= 500 loop
> PREPARE create_table(int) AS
> CREATE TABLE mbk_auth_method_$1 PARTITION OF mbk_auth_method FOR VALUES WITH (modulus 500, remainder $1);
> EXECUTE create_table (counter);
> counter := counter + 1;
> end loop;
> end$$;
>
>
> problem is that a CREATE TABLE cannot be prepared statement..
>
> Anyone know how I can accomplish the above? Seems like this is a missing
> feature - to prepare a CREATE TABLE statement..
>

This is a bad idea. You should not use PREPARE statement in plpgsql code
ever. Your code looks like from MySQL :)

do $$
begin
for i in 0..500
loop
execute format('CREATE TABLE %I PARTITION OF mbk_auth_method FOR VALUES
WITH (modulus 500, remainder %s)',
'mbk_auth_method_' || i, i);
end loop;
end;
$$;

It can be a little bit messy, but EXECUTE from the plpgsql environment is a
different statement than EXECUTE from SQL environment. Dynamic statements
are "prepared" implicitly in plpgsql. You cannot use PREPARE there.

Regards

Pavel

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message Michael Paquier 2021-01-04 10:55:11 Re: how to prepare a create table statement
Previous Message Alexander Mills 2021-01-04 04:46:19 how to prepare a create table statement