在MySql中将表和数据从一个模式复制到另一个模式的脚本

时间:2013-10-04 04:49:42

标签: mysql sql

我确定有办法做到这一点,但我还没能把各个部分放在一起。

我想:

select table_name from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = 'myschema';

然后......

for each table_name in that list
BEGIN
CREATE table myschemacopy.table_name like myschema.table_name;
INSERT INTO myschemacopy.table_nameSELECT * FROM myschema.table_name;
END LOOP

如何做到这一点?

3 个答案:

答案 0 :(得分:21)

如果它在同一台服务器上只是一个不同的数据库,则可以使用

解决方案1:

   CREATE TABLE newdb.mynewtable LIKE olddb.myoldtable;

然后,您可以使用

将数据插入旧表中
 INSERT newdb.mynewtable SELECT * FROM olddb.myoldtable;

          [or]

解决方案2

   ALTER table olddb.myoldtable rename newdb.mynewtable

答案 1 :(得分:3)

现在有点晚了但是我必须解决同样的问题,这是我提出的存储过程,以防它帮助其他人:

CREATE DEFINER=`whoever`@`wherever` PROCEDURE `copy_schema`(
    IN in_oldDB varchar(256),
    IN in_newDB varchar(256),
    IN in_copyData int(1)
)
BEGIN

DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_tname varchar(100) DEFAULT "";

DECLARE curTable CURSOR FOR 
SELECT `table_name`
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_SCHEMA = in_oldDB
and TABLE_TYPE='BASE TABLE'
;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;

set @result=NULL;

# Create new schema if it doesn't exist
SET @sql = CONCAT('CREATE SCHEMA IF NOT EXISTS ',in_newDB,';');
PREPARE create_schema FROM @sql;
EXECUTE create_schema;
DEALLOCATE PREPARE create_schema;

# Loop over tables in old schema
OPEN curTable;
clone_tables: LOOP

# get next table name
FETCH curTable INTO v_tname;

# Quit if we're done
IF v_finished = 1 THEN LEAVE clone_tables; END IF;

# Clone the table
SET @sql = CONCAT("CREATE TABLE `", in_newDB, "`.`", v_tname, "` LIKE `", in_oldDB, "`.`", v_tname, "`;");
PREPARE clone_table FROM @sql;
EXECUTE clone_table;
DEALLOCATE PREPARE clone_table;

# Optionally copy data
#select v_tname; # This just gives some feedback in workbench for long-running copies
IF (in_copyData > 0) THEN
    SET @sql = CONCAT("INSERT INTO `", in_newDB, "`.`", v_tname, "` SELECT * FROM `", in_oldDB, "`.`", v_tname, "`;");
    PREPARE clone_data FROM @sql;
    EXECUTE clone_data;
    DEALLOCATE PREPARE clone_data;
END IF;

# Result message
SET @result = IFNULL(CONCAT(@result,',',v_tname),v_tname);

END LOOP clone_tables;

# Close cursor
CLOSE curTable;

# Print result message
SELECT CONCAT("Copied the following tables from ", in_oldDB, " to ", in_newDB, ": ", @result);

END

答案 2 :(得分:-1)

只需复制下面的查询结果并运行它,或者您可以构建动态查询。

select 'select * into [newschema]. ' + table_name + ' from [myschema].' +table_name
from INFORMATION_SCHEMA.TABLES 
where TABLE_SCHEMA = 'myschema'