从现有数据库创建一个新的MySQL数据库,每个表中最多有10000行数据

时间:2015-10-23 00:13:16

标签: mysql sql stored-procedures

我正在尝试使用一些数据来创建数据库。我不需要1M +记录来做我需要的,所以我只有10000行就可以了。

我想我可以使用存储过程遍历所有表并手动创建每个表并仅插入10000行。

我创建了一个像这样的存储过程

CREATE DEFINER=`root`@`10.%` PROCEDURE `createNewDatabase`(in db_name varchar(100), in new_db_name varchar(100))
BEGIN

    DECLARE finish INT DEFAULT 0;
    DECLARE tbl VARCHAR(100);
    DECLARE cur_tables CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = db_name AND TABLE_TYPE='BASE TABLE';

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET finish = 1;

    OPEN cur_tables;

    my_loop: LOOP

        FETCH cur_tables INTO tbl;

            IF finish = 1 THEN
                LEAVE my_loop;
            END IF;

            SET @str = CONCAT('DROP TABLE IF EXISTS `', new_db_name, '`.`' , tbl , '`; CREATE TABLE `', new_db_name, '`.`' , tbl , '` LIKE `', db_name , '`.`', tbl,'`; INSERT INTO `', new_db_name , '`.`' , tbl, '` SELECT * FROM `', db_name ,'`.`', tbl , '` LIMIT 10000;');


            PREPARE stmt FROM @str;
            EXECUTE stmt;

            DEALLOCATE PREPARE stmt;

        END LOOP;

    CLOSE cur_tables;

END

然后我这样称呼它 CALL createNewDatabase('baseTable','newTable');

但我运行程序时出现以下错误

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CREATE TABLE `newTable`.`account_addresses` LIKE `baseTable`.`account_addres' at line 1

如果我在准备声明之前添加了以下2行

SELECT @str;
LEAVE my_loop;

如果我手动执行这些查询,我会得到以下查询

DROP TABLE IF EXISTS `newTable`.`account_addresses`; 
CREATE TABLE `newTable`.`account_addresses` LIKE `baseTable`.`account_addresses`; 
INSERT INTO `newTable`.`account_addresses` SELECT * FROM `newTable`.`account_addresses` LIMIT 10000;

CREATE TABLE `newTable`.`account_addresses` LIKE `baseTable`.`account_addresses`; INSERT INTO `newTable`.`account_addresses` SELECT * FROM `baseTable`.`account_addresses` LIMIT 10000;

我在这里做错了什么?为什么会出错?

1 个答案:

答案 0 :(得分:0)

引用mysql在PREPARE上的文档:

  

文本必须代表单个陈述,而不是多个陈述。

您正在尝试执行drop table和create table语句,在1个预准备语句中插入记录,这是不允许的。为3个命令准备3个单独的准备语句。