MYSQL批量创建表的存储过程
因为业务需要,创建了100个表,但是这些表的结构都是一样的,作为程序员,就是要解决这种重复劳动。然而这种事情还要单独写个php脚本的话太麻烦了吧,所以就干脆学了一下直接用Mysql存储过程怎么实现:
首先是创建表的:( LPAD(`@i`, 2, '0')的作用 是将1,2,3这些数字转化为'01','02','03')
DROP PROCEDURE IF EXISTS `create_tables`; CREATE PROCEDURE create_tables () BEGIN DECLARE `@i` INT (11); DECLARE `@createSql` VARCHAR (2560);SET `@i` = 0; WHILE `@i` < 100 DO -- 创建表 SET @createSql = CONCAT( "CREATE TABLE IF NOT EXISTS guess_record", LPAD(`@i`, 2, '0'), "( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `userid` int(12) unsigned NOT NULL COMMENT '用户ID', `issue` int(10) unsigned NOT NULL COMMENT '期号', `options_id` int(10) unsigned NOT NULL COMMENT '选项ID', `guess_time` int(10) unsigned NOT NULL COMMENT '答题时间', `is_stat` tinyint(4) NOT NULL COMMENT '是否统计过', PRIMARY KEY (`id`), KEY `issue` (`issue`) USING BTREE, KEY `userid` (`userid`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; " ); PREPARE stmt FROM @createSql; EXECUTE stmt; SET `@i` = `@i` + 1; END WHILE; END
然后是批量删除表的(嘿嘿,搞事情)
DROP PROCEDURE IF EXISTS `drop_tables`; CREATE PROCEDURE drop_tables () BEGIN DECLARE `@i` INT (11); DECLARE `@dropSql` VARCHAR (2560); SET `@i` = 0; WHILE `@i` < 100 DO -- 创建表 SET @dropSql = CONCAT("DROP TABLE IF EXISTS guess_record",LPAD(`@i`, 2, '0')); PREPARE stmt FROM @dropSql; EXECUTE stmt; SET `@i` = `@i` + 1; END WHILE; END
我用这个存储过程其实就是一次性的,所以完整的过程是 1、创建存储过程 2、执行存储过程(批量创建表)3、删除存储过程
#1:创建存储过程 DROP PROCEDURE IF EXISTS `create_tables`; DELIMITER $$ //定义结束符 CREATE PROCEDURE create_tables () BEGIN DECLARE `@i` INT (11); DECLARE `@createSql` VARCHAR (2560); SET `@i` = 0; WHILE `@i` < 100 DO -- 创建表 SET @createSql = CONCAT( "CREATE TABLE IF NOT EXISTS guess_record", LPAD(`@i`, 2, '0'), "( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `userid` int(12) unsigned NOT NULL COMMENT '用户ID', `issue` int(10) unsigned NOT NULL COMMENT '期号', `options_id` int(10) unsigned NOT NULL COMMENT '选项ID', `guess_time` int(10) unsigned NOT NULL COMMENT '答题时间', `is_stat` tinyint(4) NOT NULL COMMENT '是否统计过', PRIMARY KEY (`id`), KEY `issue` (`issue`) USING BTREE, KEY `userid` (`userid`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; " ); PREPARE stmt FROM @createSql; EXECUTE stmt; SET `@i` = `@i` + 1; END WHILE; END $$ DELIMITER ; //结束符改为; #2:执行存储过程 CALL `create_tables`(); #3:删除存储过程 DROP PROCEDURE IF EXISTS `create_tables`;