mysql分区表人为添加不可控性太大,如果出现人员变动交接不利,或者遗忘,会导致业务数据丢失或写入失败,同时如果使用分区表较多,逐个添加分区也是挺麻烦的
推荐使用存储过程+event自动添加,同时需要留足作业时间间隔,以防万一出翔没有补救的时间,我设置的是每月初自动生成下月分区,由于我设计的分区表均为range分区按to_days设置,如果有不同需求,可以在游标内添加条件筛选,或者直接写表名过滤
1 CREATE PROCEDURE `sp_add_table_partition`(in p_startdate date,in p_enddate date,out p_status int) 2 BEGIN 3 DECLARE v_startdate int DEFAULT 0; 4 DECLARE v_enddate int DEFAULT 0; 5 DECLARE v_maxpart int DEFAULT 0; 6 DECLARE v_table varchar(50); 7 DECLARE v_cnt int DEFAULT 0; 8 DECLARE done int DEFAULT 0; 9 DECLARE v_cursor CURSOR FOR 10 ( 11 select TABLE_NAME,max(REPLACE(partition_name,‘p‘,‘‘)) FROM INFORMATION_SCHEMA.PARTITIONS 12 where PARTITION_NAME is not null 13 group by TABLE_NAME 14 ); 15 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; 16 DECLARE EXIT HANDLER FOR SQLEXCEPTION 17 begin 18 ROLLBACK; 19 set autocommit=1; 20 set p_status=0; 21 show errors; 22 end; 23 set autocommit=0; 24 25 label_a:BEGIN 26 SET v_startdate=TO_DAYS(p_startdate); 27 SET v_enddate=TO_DAYS(p_enddate); 28 29 OPEN v_cursor; 30 f_loop:LOOP 31 FETCH v_cursor INTO v_table,v_maxpart; 32 33 IF done THEN 34 LEAVE f_loop; 35 END IF; 36 37 if v_startdate>=v_enddate then 38 set p_status=2; 39 LEAVE label_a; 40 end if; 41 42 if v_startdate<=TO_DAYS(v_maxpart) then 43 set p_status=3; 44 LEAVE label_a; 45 end if; 46 47 if v_enddate<=TO_DAYS(v_maxpart) then 48 set p_status=4; 49 LEAVE label_a; 50 end if; 51 52 set v_cnt=v_enddate-TO_DAYS(v_maxpart); 53 54 set @i=1; 55 WHILE @i<v_cnt do 56 57 SET @Max_date= DATE(DATE_ADD(v_maxpart+0, INTERVAL @i DAY))+0; 58 59 SET @sql_1=CONCAT(‘ALTER TABLE ‘,v_table,‘ ADD PARTITION (PARTITION p‘,@Max_date,‘ VALUES LESS THAN (TO_DAYS (‘‘‘,@Max_date,‘‘‘)))‘); 60 61 PREPARE stmt2 FROM @sql_1; 62 EXECUTE stmt2; 63 DEALLOCATE PREPARE stmt2; 64 65 SET @i=@i+1; 66 set p_status=1; 67 END WHILE; 68 69 end LOOP f_loop; 70 71 CLOSE v_cursor; 72 73 END; 74 COMMIT; 75 set autocommit=1; 76 77 78 END
1 CREATE DEFINER=`odao_yunwei1`@`%` EVENT `event_add_table_partition` ON SCHEDULE EVERY 1 MONTH STARTS ‘2018-01-01 00:00:00‘ ON COMPLETION PRESERVE ENABLE DO call sp_add_table_partition(DATE_ADD(DATE(NOW()),INTERVAL 1 MONTH),DATE_ADD(DATE(NOW()),INTERVAL 2 MONTH),@a)