简体   繁体   中英

How do I create a table for all tables in MySQL

I'm using MySQL for C++ and I want to create a new table for all the tables in my second database. The code I have now is:

CREATE TABLE new_table LIKE original_table;

INSERT INTO new_table SELECT * FROM original_table;

I want to this to work like a loop where all the tables and data in those tables are created for every table and piece of data there is in my second database. Can someone help me?

We can use a stored procedure to do the job in a loop. I just wrote the code and tested it in workbench. Got all my tables(excluding view) from sakila database to my sakila_copy database:

use testdb;
delimiter //
drop procedure if exists copy_tables //
create procedure copy_tables(old_db varchar(20),new_db varchar(20))
begin
declare tb_name varchar(30);
declare fin bool default false;
declare c cursor for select table_name from information_schema.tables where table_schema=old_db and table_type='BASE TABLE';
declare continue handler for not found set fin=true;

open c;

lp:loop
fetch c into tb_name;

if fin=true then
leave lp;
end if;


set @create_stmt=concat('create table ',new_db,'.',tb_name,' like ',old_db,'.',tb_name,';') ;
prepare ddl from @create_stmt;
execute ddl;
deallocate prepare ddl; 

set @insert_stmt=concat('insert into ',new_db,'.',tb_name,' select * from ',old_db,'.',tb_name,';');
prepare dml from @insert_stmt;
execute dml;
deallocate prepare dml; 

end loop lp;

close c;
end//

delimiter ;

create database sakila_copy;

call testdb.copy_tables('sakila','sakila_copy');

-- after the call, check the tables in sakila_copy to find the new tables
show tables in sakila_copy;

Note: As I stated before, only base tables are copied. I deliberately skipped views, as they provide logical access to tables and hold no data themselves.

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