Is it possible to create a table with a variable name in PostgreSQL?

淺唱寂寞╮ 提交于 2019-12-23 15:02:57

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/941245/is-it-possible-to-create-a-table-with-a-variable-name-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!