mysql 按天创建分区存储过程
CREATE PROCEDURE `create_partition_by_day`(IN_SCHEMANAME VARCHAR(64), IN_TABLENAME VARCHAR(64)) BEGIN #当前日期存在的分区的个数 DECLARE ROWS_CNT INT UNSIGNED; #目前日期,为当前日期的后一天 DECLARE TARGET_DATE TIMESTAMP; #分区的名称,格式为p20180620 DECLARE PARTITIONNAME VARCHAR(9); #当前分区名称的分区值上限,即为 PARTITIONNAME + 1 DECLARE PARTITION_ADD_DAY VARCHAR(9); SET TARGET_DATE = NOW() + INTERVAL 1 DAY; SET PARTITIONNAME = DATE_FORMAT( TARGET_DATE, 'p%Y%m%d' ); SET TARGET_DATE = TARGET_DATE + INTERVAL 1 DAY; SET PARTITION_ADD_DAY = DATE_FORMAT( TARGET_DATE, '%Y%m%d' ); SELECT COUNT(*) INTO ROWS_CNT FROM information_schema.partitions WHERE table_schema = IN_SCHEMANAME AND table_name = IN_TABLENAME AND partition_name = PARTITIONNAME; IF ROWS_CNT = 0 THEN SET @SQL = CONCAT( 'ALTER TABLE `', IN_SCHEMANAME, '`.`', IN_TABLENAME, '`', ' ADD PARTITION (PARTITION ', PARTITIONNAME, " VALUES LESS THAN (", PARTITION_ADD_DAY ,") ENGINE = InnoDB);" ); PREPARE STMT FROM @SQL; EXECUTE STMT; DEALLOCATE PREPARE STMT; ELSE SELECT CONCAT("partition `", PARTITIONNAME, "` for table `",IN_SCHEMANAME, ".", IN_TABLENAME, "` already exists") AS result; END IF; END
#分区范围
PARTITION BY RANGE (YEAR(request_time)*10000+MONTH(request_time)*100+DAY(request_time))
#调用刚才创建的存储过程,第一个参数是数据库名称,第二个参数是表名称
CALL create_partition_by_day('test','test');