mysql表根据时间戳字段创建表分区的存储过程

这篇文章与mysql存储过程按月创建表分区 方式一 写的是相同的内容,只是在表分区创建方式上不一样。 标题已经写的很清楚了,直接贴sql语句啦。

-- 普通添加第一个表分区语句
ALTER TABLE iot_divice_info PARTITION by range(UNIX_TIMESTAMP(createtime))(partition par0 values less than (UNIX_TIMESTAMP('2016-02-01 00:00:00')));
-- 普通添加表分区语句
ALTER TABLE iot_divice_info add partition (partition par1 values less than (UNIX_TIMESTAMP('2016-03-01 00:00:00')));

--通过时间戳类型的字段对表分区存储过程
create PROCEDURE pro_sys_logByMonthSJC(IN tableName VARCHAR(20),IN timeColName VARCHAR(20))
COMMENT '每月按时添加表分区的存储过程,由定时任务调用'
BEGIN
    DECLARE p_id int;
    DECLARE nextDate date;
    DECLARE lastDate LONG;
    --获取表中的现有的分区数量数量
    SELECT COUNT(partition_name) into p_id FROM INFORMATION_SCHEMA.partitions 
                                        WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME=tableName;
    if p_id=0 then
        --获取下个月第一天的时间值,根据此值设置时间分区
        SELECT DATE_ADD(CURDATE()-DAY(CURDATE())+1,INTERVAL 1 MONTH) into nextDate from DUAL; 
        set @v_add=CONCAT('ALTER table ',tableName,' PARTITION by range(UNIX_TIMESTAMP(',timeColName,'))
                                    (partition ',CONCAT('par',p_id),' values less than (UNIX_TIMESTAMP(\'',nextDate,'\')))');
    ELSE
        --获取表中现有的最大的分区日期
        SELECT max(partition_description) des into lastDate from INFORMATION_SCHEMA.partitions 
                WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME=tableName;
        --获取下个月第一天的时间值,根据此值设置时间分区
        select DATE_ADD(FROM_UNIXTIME(lastDate),INTERVAL 1 MONTH)  into nextDate  from dual;
        set @v_add=CONCAT('alter table ',tableName,' add partition (partition ',CONCAT('par',p_id),
                        ' values less than (UNIX_TIMESTAMP(\'',nextDate,'\')))');
    END IF;
    PREPARE stmt from @v_add;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END;
-- 测试存储过程
call pro_sys_logByMonthSJC('iot_divice_info','createtime');
-- 删除表分区
ALTER TABLE iot_divice_info REMOVE PARTITIONING; 

--每月创建一个分区的定时任务
create event event_sysLog on SCHEDULE EVERY 1 MONTH STARTS CURRENT_TIMESTAMP
on COMPLETION PRESERVE
ENABLE
do call pro_sys_logByMonthSJC('sys_log_storage','createtime');

一个刚升级为奶爸码农的个人整理。

你可能感兴趣的:(mysql)