通过存储过程迁移当前表分区数据到历史表
- 记录另外一种非常简单的方法,来迁移当前表分区数据到历史表。
- 当表名或表分区是变量时,sql应该如何编写;
- 存储过程还包含调试信息,如select @transTime,可打印变量值。
- 存储过程有三个变量,分别是迁移数据时间,当前表名,历史表名。
- 增加了事务一致性的控制,如果迁移数据异常,则当前表的数据不会被删除。
- 增加了存储过程的耗时记录和迁移记录,每次迁移都会被记录到表中,可随时观察迁移的数据量,迁移时间,迁移的表名,迁移状态等。
存储过程
CREATE PROCEDURE `transLogMoveProc2`(in beforMonth int, in currentTableName varchar(32), in hisTableName varchar(32))
BEGIN
DECLARE all_count int default 0;
DECLARE error_status INTEGER DEFAULT 1;
DECLARE execute_status INT DEFAULT FALSE;
declare partName VARCHAR(200);
declare sqlStmt VARCHAR(200);
declare sqlStmt2 VARCHAR(200);
declare sqlStmt3 VARCHAR(200);
DECLARE diffTime int default 0;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET error_status=-1;
set beginTime = DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S');
set transTime = DATE_SUB(beginTime,INTERVAL beforMonth MONTH);
set partName = CONCAT('P',SUBSTR(DATE_FORMAT(transTime,'%Y%m') FROM 3 FOR 6));
set @sqlStmt = CONCAT("select count(1) from ", currentTableName, " PARTITION( ",partName, ") into @all_count ;") ;
PREPARE stmt from @sqlStmt;
EXECUTE stmt;
START TRANSACTION;
set @sqlStmt2 = CONCAT("insert into ",hisTableName, " select * from ", currentTableName, " PARTITION(",partName ,");") ;
set @sqlStmt3 = CONCAT("alter table ", currentTableName, " TRUNCATE1 PARTITION ",partName ,";") ;
PREPARE stmt2 from @sqlStmt2;
EXECUTE stmt2;
PREPARE stmt3 from @sqlStmt3;
EXECUTE stmt3;
IF(error_status = -1) THEN
ROLLBACK;
ELSE
COMMIT;
set execute_status = TRUE;
END IF;
set endTime = DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S');
set diffTime = TIMESTAMPDIFF(SECOND,beginTime,endTime);
insert into t_move_log(`move_count`,`current_Table`,`his_Table`,`begin_time`,`end_time`,`use_time`, `create_time`, `move_status`) VALUES (@all_count,currentTableName, hisTableName, beginTime, endTime, diffTime,DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S'), execute_status);
END