MySQL event實現定時建表小記

來源:互聯網
上載者:User

MySQL event實現定時建表小記

MySQL event實現定時建表小記

每天淩晨一點建一個第二天的表
DELIMITER //
 CREATE PROCEDURE test.create_tab_every_day()
 BEGIN
 DECLARE `@i` VARCHAR(15);
 DECLARE `@sqlstr` VARCHAR(2560);
 SET `@i` = DATE_FORMAT(DATE_ADD(NOW(),INTERVAL 1 DAY),'%Y_%m_%d');
 SET @sqlstr = CONCAT(
 "CREATE TABLE day_tab_",
 `@i`,
 "(
  `prop` VARCHAR(40)
 );"
 );
 PREPARE stmt FROM @sqlstr;
 EXECUTE stmt;
 END;

 CALL test.create_tab_every_day();
 /*****DROP PROCEDURE test.create_tab_every_day;*****/
 /*****drop table test.day_tab_2015_09_11;*****/

 DELIMITER $$
 CREATE EVENT event_create_tab_days
 ON SCHEDULE EVERY 1 DAY
 STARTS '2015-09-10 01:00:00'
 ON  COMPLETION  PRESERVE
 ENABLE
 DO
 BEGIN
 CALL test.create_tab_every_day();
 END
 $$
 DELIMITER ;


每月的11號建一張下個月的表

DELIMITER //
 CREATE PROCEDURE test.create_tab_every_mon()
 BEGIN
 DECLARE `@i` VARCHAR(15);
 DECLARE `@sqlstr` VARCHAR(2560);
 SET `@i` = DATE_FORMAT(DATE_ADD(NOW(),INTERVAL 1 MONTH),'%Y_%m');
 SET @sqlstr = CONCAT(
 "CREATE TABLE mon_tab_",
 `@i`,
 "(
  `prop` VARCHAR(40)
 );"
 );
 PREPARE stmt FROM @sqlstr;
 EXECUTE stmt;
 END;


 CALL test.create_tab_every_mon();
 /*****DROP PROCEDURE test.create_tab_every_mon;*****/
 /*****DROP TABLE test.mon_tab_2015_10*****/


 DELIMITER $$
 CREATE EVENT event_create_tab_mons
 ON SCHEDULE EVERY 1 MONTH
 STARTS '2015-09-11 01:00:00'
 ON  COMPLETION  PRESERVE
 ENABLE
 DO
 BEGIN
 CALL test.create_tab_every_mon();
 END
 $$
 DELIMITER ;

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.