3

我确信有办法做到这一点,但我无法将这些部分组合在一起。

我想:

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

如何才能做到这一点?

4

3 回答 3

31

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

解决方案 1:

   CREATE TABLE newdb.mynewtable LIKE olddb.myoldtable;

然后,您可以使用旧表将数据插入到新表中

 INSERT newdb.mynewtable SELECT * FROM olddb.myoldtable;

          [or]

解决方案 2

   ALTER table olddb.myoldtable rename newdb.mynewtable
于 2014-10-28T05:26:52.800 回答
5

有点晚了,但刚刚解决了同样的问题,这是我想出的存储过程,以防它帮助别人:

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
于 2015-08-28T20:11:10.783 回答
-3

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

select 'select * into [newschema]. ' + table_name + ' from [myschema].' +table_name
from INFORMATION_SCHEMA.TABLES 
where TABLE_SCHEMA = 'myschema'
于 2013-10-04T04:59:30.180 回答