繁体   English   中英

如何为MySQL中的所有表创建一个表

[英]How do I create a table for all tables in MySQL

我将 MySQL 用于 C++,我想为第二个数据库中的所有表创建一个新表。 我现在的代码是:

CREATE TABLE new_table LIKE original_table;

INSERT INTO new_table SELECT * FROM original_table;

我希望它像一个循环一样工作,其中所有表和这些表中的数据都是为我的第二个数据库中的每个表和数据块创建的。 有人能帮我吗?

我们可以使用存储过程来循环完成这项工作。 我刚刚编写了代码并在工作台中对其进行了测试。 将我所有的表(不包括视图)从sakila数据库获取到我的sakila_copy数据库:

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;

注意:如前所述,仅复制基表。 我故意跳过视图,因为它们提供对表的逻辑访问并且本身不保存数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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