delimiter // CREATEprocedure create_table() BEGIN DECLARE i INT; DECLARE table_name VARCHAR(200); DECLARE table_pre VARCHAR(200); DECLARE sql_text VARCHAR(10000); SET i=1; SET table_name=''; SET table_pre='log_201801'; SET sql_text='';
while i<32 do
IF i<10THENSET table_name=CONCAT(table_pre,"0",i); ELSESET table_name=CONCAT(table_pre,i); END IF;
SET sql_text=CONCAT('CREATE TABLE ', table_name, '( `ID` int(11) NOT NULL AUTO_INCREMENT, `event_name` varchar(32) NOT NULL, `Log_Time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`ID`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8' );
end while; END; call create_table(); dropprocedure create_table; //
也可以创建一个存储过程,然后通过事件调度每天 00:00:00 执行:
1 2 3 4 5 6 7 8 9 10 11 12
CREATEPROCEDURE `create_log_table`() BEGIN set@sqlstr=CONCAT('CREATE TABLE IF NOT EXISTS `log_',DATE_FORMAT(NOW(),'%Y%m%d'),'` ( `id` int(10) AUTO_INCREMENT NOT NULL,`Gboard_UUID` varchar(32) NOT NULL,`Channel` varchar(4) NOT NULL, `event_name` varchar(32) NOT NULL, `Log_Time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) )ENGINE=MyISAM DEFAULT CHARSET=utf8;'); PREPARE create_stmt from@sqlstr; EXECUTE create_stmt;
END
事件
1
CREATE EVENT `create_log_daily` ON SCHEDULE EVERY1DAY STARTS '2018-01-01 00:00:00'ON COMPLETION PRESERVE ENABLE DO CALL create_log_table()