简体   繁体   中英

Programmatically create a new table from anothers (Postgres)

I have 32 tables with the exactly the same schema (ie same columns names, etc.) in a PostgreSQL 9.1 data base, and I want to create a new table from them (so I can unify the queries).

I know that I can use a INSERT SELECT technique, table by table, but I was wondering if its a better way of do that. Maybe a for loop?

Thanks in advance

Maybe something like this should work, if your tables really have the same column names and types:

SELECT 'INSERT INTO myschema.mynewtable SELECT * FROM ' || table_schema || '.' || table_name || ';'
  FROM information_schema.tables 
  WHERE table_schema='myschema' AND table_name LIKE 'old%';

This will output the INSERT statements you can then execute to insert the data from the old tables. It would be possible to automatically execute them using a PL/SQL procedure. But if you need to do that just once, I think it's easier to execute them manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM