MYSQL定时创建表分区
MYSQL定时创建表分区
一.存储过程-表分区
-----------------------------------------------------------------
需求:
每月创建一个分区
分区名名称格式:p201201,p201202……
------------------------------------------
1 CREATE DEFINER = `root`@`%` PROCEDURE `Auto_Create_Partition`(IN `databaseName` varchar(50),IN `tableName` varchar(50)) 2 L_END:BEGIN 3 # 初始化变量 4 DECLARE MAX_PARTITION_DESCRIPTION VARCHAR(255) DEFAULT 0; 5 DECLARE P_DESCRIPTION VARCHAR(255) DEFAULT 0; 6 DECLARE i INT DEFAULT 1; 7 DECLARE ISEXIST_PARTITION VARCHAR(255) DEFAULT 0; 8 DECLARE next_p_name varchar(255) DEFAULT 0; 9 # 查询表分区 最近的一个月的分区(ORDER BY partition_description DESC LIMIT 1) 10 SELECT PARTITION_NAME INTO ISEXIST_PARTITION FROM information_schema.PARTITIONS WHERE TABLE_SCHEMA = databaseName AND TABLE_NAME = tableName ORDER BY partition_description DESC LIMIT 1 ; 11 12 IF ISEXIST_PARTITION <=> "" THEN 13 SELECT "Partition table not is exist" AS "*****ERROR*****"; 14 LEAVE L_END; 15 END IF; 16 17 # 根据时间设置要创建的分区的名称 18 SELECT concat('p',DATE_FORMAT(DATE_ADD(NOW(),INTERVAL 1 MONTH),'%Y%m')) INTO next_p_name; 19 20 # 判断要创建的分区是否存在 21 IF ISEXIST_PARTITION = next_p_name THEN 22 SELECT concat("Partition(",next_p_name,") is exist") AS "*****INFO*****"; 23 LEAVE L_END; 24 END IF; 25 26 # 最近一个分区的设置的最大值(右边界) 27 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; 28 29 IF MAX_PARTITION_DESCRIPTION <=> "" THEN 30 SELECT "Partition table is error" AS "*****ERROR*****"; 31 LEAVE L_END; 32 END IF; 33 34 # 创建新的分区 35 # 1.设置新的分区的右边界值 36 SET P_DESCRIPTION = TO_DAYS(DATE_FORMAT(DATE_ADD(NOW(),INTERVAL 2 MONTH),'%Y%m01')); 37 # 2.拼接新增分区的SQL语句 38 SET @S=CONCAT('ALTER TABLE ',tableName,' ADD PARTITION (PARTITION ',next_p_name,' VALUES LESS THAN (',P_DESCRIPTION,'))'); 39 SELECT @S; 40 # 3.使用预处理执行SQL 41 # ------------------------------------------------------------------------------------------ 42 # 语法:语法 43 # PREPARE statement_name FROM sql_text /*定义*/ 44 # EXECUTE statement_name [USING variable [,variable...]] /*执行预处理语句*/ 45 # DEALLOCATE PREPARE statement_name /*删除定义*/ 46 # ------------------------------------------------------------------------------------------ 47 PREPARE stmt2 FROM @S; 48 EXECUTE stmt2; 49 DEALLOCATE PREPARE stmt2; 50 51 END L_END
-----------------------------------------------------------------------
二.定时事件创建