7

Using PL/pgSQL or (some other mechanism), is it possible to create a table with a variable name?

I would like to create multiple tables named table_1, table_2, table_3, etc... and it would be simpler if I could use a loop to create them, instead of explicitly creating each one.

I suspect the answer to this is no, but I would like to confirm it.

2 Answers 2

4

While I would question your design if you're relying on such tricks, your question is general and you didn't give specific information to judge either way.

It should be possible, actually. It's only a matter of programmatically building the table names as strings and then, in a loop, execute your CREATE statements as dynamic queries.

See this page in the postgres documentation: http://www.postgresql.org/docs/current/interactive/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the link. I need to create multiple tables because I need will be using table partitions on an existing table.
Looks like dynamic queries is what I need. Thanks!
0

Generate a script by building the commands dynamically in a loop, then run the resulting output script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.