mysql 多分区,自动化分区脚本
Posted TT_DUL
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 多分区,自动化分区脚本相关的知识,希望对你有一定的参考价值。
**以下为mysql 自动化分区脚本,但是要配合mysql 事件去触发 的,详细为每天一个分区,每个月的11号去增加下一个月的所有分区,格式具体 为: add partition(partition p20160601 values less than (20160601235959));
另外特别特别要注意的是要查看你的mysql 是否启用了 事件
show variables like ‘%scheduler%’;
如果没有启用,那么此时需要到mysql配置文件my.cnf新增一项,在mysqld后面添加event_scheduler = on(或是event_scheduler = 1),保存后重启mysql服务器即可。
当然也可以使用 *
set global event_scheduler = on;*
1、自动化分区脚本
DELIMITER $$
DROP PROCEDURE IF EXISTS `xxx`.`create_Partition`$$
CREATE DEFINER=`root`@`%` PROCEDURE `create_Partition`(IN databaseName VARCHAR(50),IN tableName VARCHAR(50))
L_END:BEGIN
DECLARE MAX_PARTITION_DESCRIPTION VARCHAR(255) DEFAULT 0;
DECLARE P_NAME VARCHAR(255) DEFAULT 0;
DECLARE P_DESCRIPTION VARCHAR(255) DEFAULT 0;
DECLARE i INT DEFAULT 1;
DECLARE ISEXIST_PARTITION VARCHAR(255) DEFAULT 0;
DECLARE MONTH_DAYS VARCHAR(5);
DECLARE YEAR_NUM VARCHAR(10);
DECLARE MONTH_NUM VARCHAR(5);
SELECT PARTITION_NAME INTO ISEXIST_PARTITION FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = databaseName AND TABLE_NAME = tableName LIMIT 1 ;
IF ISEXIST_PARTITION <=> "" THEN
SELECT "Partition table not is exist" AS "*****ERROR*****";
LEAVE L_END;
END IF;
SELECT partition_description INTO MAX_PARTITION_DESCRIPTION FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = databaseName AND TABLE_NAME = tableName ORDER BY partition_description DESC LIMIT 1;
IF MAX_PARTITION_DESCRIPTION <=> "" THEN
SELECT "Partition table is error" AS "*****ERROR*****";
LEAVE L_END;
END IF;
select day(last_day(date_add(NOW(), interval 1 MONTH)))into MONTH_DAYS;
SET MAX_PARTITION_DESCRIPTION = REPLACE(MAX_PARTITION_DESCRIPTION, '\\'', '');
WHILE i <= MONTH_DAYS DO
select date_format(date_add(last_day(NOW()),interval i day),'%Y%m%d') into P_DESCRIPTION;
## SET P_DESCRIPTION = adddate(MAX_PARTITION_DESCRIPTION, INTERVAL i day);
SET P_NAME = REPLACE(P_DESCRIPTION, '-', '');
SET @S=CONCAT('ALTER TABLE ',tableName,' ADD PARTITION (PARTITION p',P_NAME,' VALUES LESS THAN (',P_DESCRIPTION,'235959))');
SELECT @S;
PREPARE stmt2 FROM @S;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
SET i = i + 1 ;
END WHILE;
END L_END$$
DELIMITER ;
2、mysql 自动化分区脚本触发事件
DELIMITER $$
CREATE DEFINER=`root`@`%` EVENT `auto_set_partitions` ON SCHEDULE EVERY 1 MONTH STARTS '2016-06-11 17:18:00' ON COMPLETION PRESERVE ENABLE DO BEGIN
CALL create_Partition('xxx','testable')$$
END
DELIMITER ;
以上是关于mysql 多分区,自动化分区脚本的主要内容,如果未能解决你的问题,请参考以下文章