mysql 批量创建表,利用存储过程

时间:2023-12-22 14:30:20

最近根据需求,需要提前创建一批日志表,以日期结尾,每天创建一张,例如XXX20160530,请参考如下:

BEGIN  
 
DECLARE `sName` VARCHAR(128);   
DECLARE `sqlVar` VARCHAR(1024);  
DECLARE `rest` INT;  
 
set rest = 1;

while rest > 0 do  
    
 set sTime = (select DATE_FORMAT((select ADDDATE(sTime,1)),'%Y%m%d'));  
 set sName = CONCAT('XXX',sTime);  
 
 select count(1) from information_schema.tables where table_name = sName and TABLE_SCHEMA=tchema into @cnt;  
 if @cnt = 0 then    
 
        set sqlVar=CONCAT(" create table ",sName,  
                    "(code varchar(255),
        userCode varchar(255) COMMENT 'XXX',
        roleCode varchar(20) COMMENT 'XXX',
        createTime varchar(100) COMMENT '创建时间',
        url varchar(255) COMMENT '接口名称url',
        parameter1 varchar(255) COMMENT '保留字段1,暂时做版本字段',
        parameter2 varchar(255) COMMENT '保留字段2',
        parameter3 varchar(255) COMMENT '保留字段3',
        parameter4 varchar(255) COMMENT '保留字段4',
        kindergartenCode varchar(255) COMMENT 'XXX',
        sum int(11) COMMENT '访问次数',
    shardingName varchar(255) COMMENT 'XXX'
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='XXX'");  
 
        set @v_s=sqlVar;  
        prepare stmt from @v_s;  
        EXECUTE stmt;  
        DEALLOCATE PREPARE stmt;  
END if;  
 
 set rest = DATEDIFF(eTime,sTime);  
 
END while;  
 
END

运行参数:'20160529','20170530','hadoop'    分别对应:sTime,eTime,tchema