對test
數據庫中position
表按日期(天)分區:
需要做:
- 對已有數據分區
- 添加過程存儲(相當於函數)
- 添加事件(相當於定時調用函數)
-
開啟事件調度器(默認關閉)
SET GLOBAL event_scheduler = ON;
-
必須對已有數據先進行分區
ALTER TABLE position PARTITION BY RANGE(TO_DAYS(date)) ( PARTITION p20181028 VALUES LESS THAN (TO_DAYS('2018-10-29')), PARTITION p20181029 VALUES LESS THAN (TO_DAYS('2018-10-30')), PARTITION p20181030 VALUES LESS THAN (TO_DAYS('2018-10-31')) )
-
分區腳本
use test; DELIMITER || -- 刪除存儲過程 drop procedure if exists auto_set_partitions || -- 注意:使用該存儲過程必須保證相應數據庫表中至少有一個手動分區 -- 創建存儲過程[通過數據庫名和對應表名]-建多少個分區,分區時間間隔為多少 -- databasename:創建分區的數據庫 -- tablename:創建分區的表的名稱 -- partition_number:一次創建多少個分區 -- partitiontype:分區類型[0按天分區,1按月分區,2按年分區] -- gaps:分區間隔,如果分區類型為0則表示每個分區的間隔為 gaps天; -- 如果分區類型為1則表示每個分區的間隔為 gaps月 -- 如果分區類型為2則表示每個分區的間隔為 gaps年 create procedure auto_set_partitions (in databasename varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,in tablename varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, in partition_number int, in partitiontype int, in gaps int) L_END: begin declare max_partition_description varchar(255) default ''; declare p_name varchar(255) default 0; declare p_description varchar(255) default 0; declare isexist_partition varchar(255) default 0; declare i int default 1; -- 查看對應數據庫對應表是否已經有手動分區[自動分區前提是必須有手動分區] select partition_name into isexist_partition from information_schema.partitions where table_schema = databasename and table_name = tablename limit 1; -- 如果不存在則打印錯誤並退出存儲過程 if isexist_partition <=> "" then select "partition table not is exist" as "ERROR"; leave L_END; end if; -- 獲取最大[降序獲取]的分區描述[值] select partition_description into max_partition_description from information_schema.partitions where table_schema = databasename and table_name = tablename order by partition_description desc limit 1; -- 如果最大分區沒有,說明沒有手動分區,則無法創建自動分區 if max_partition_description <=> "" then select "partition table is error" as "ERROR"; leave L_END; end if; -- 替換前后的單引號[''兩個引號表示一個單引號的轉義] -- set max_partition_description = REPLACE(max_partition_description, '''', ''); -- 或使用如下語句 set max_partition_description = REPLACE(max_partition_description-1, '\'', ''); -- 自動創建number個分區 while (i <= partition_number) do if (partitiontype = 0) then -- 每個分區按天遞增,遞增gaps天 set p_description = DATE_ADD(FROM_DAYS(max_partition_description), interval i*gaps day); elseif (partitiontype = 1) then -- 每個分區按月遞增,遞增gaps月 set p_description = DATE_ADD(FROM_DAYS(max_partition_description), interval i*gaps month); else -- 每個分區按年遞增,遞增gaps年 set p_description = DATE_ADD(FROM_DAYS(max_partition_description), interval i*gaps year); end if; -- 刪除空格 set p_name = REPLACE(p_description, ' ', ''); -- 例如10.20的記錄實際是less than 10.21 set p_description = DATE_ADD(p_description, interval 1 day); -- 如果有橫桿替換為空 set p_name = REPLACE