批量動態新增分區表
阿新 • • 發佈:2018-01-22
range分區 麻煩 creat 條件篩選 exc interval errors pro rom
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‘,‘‘)) FROMINFORMATION_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 setautocommit=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)
批量動態新增分區表