Stored Procedure for Mysql Rebuild/Analyze Table
DROP procedure IF EXISTS `usp_rebuild`;
DELIMITER $$
CREATE PROCEDURE `usp_rebuild`(size bigint(21) unsigned)
BEGIN
-- call usp_rebuild_v4(5242880); 5Mb
DECLARE querycount INT;
DECLARE currentRow INT;
DECLARE total_time time;
drop temporary table if exists temp_rebuildtables;
-- create temporary table temp_rebuildtables(id int auto_increment primary key , script varchar(64) );
create temporary table temp_rebuildtables(id int NOT NULL AUTO_INCREMENT PRIMARY KEY, db_name varchar(64) not null,t_name varchar(64) not null,Actual_size bigint(21) unsigned,free_space bigint(21) unsigned,script varchar (120) );
insert into temp_rebuildtables (db_name, t_name,Actual_size,free_space,script)
SELECT table_schema,table_name,(data_length + index_length) Data_Size,DATA_FREE,concat('OPTIMIZE TABLE ',table_schema,'.',table_name,';') as sc
FROM `information_schema`.`tables` WHERE `table_schema` not in (
'information_schema',
'mysql',
'performance_schema',
'sys',
'mysql_innodb_cluster_metadata') and table_type='BASE Table' and table_name not in ('emaillog')and DATA_FREE > size order by DATA_FREE desc ;
select count(script) into querycount from temp_rebuildtables limit 1;
SET currentRow = 1;
WHILE currentRow <= querycount DO
set @qry1:= (SELECT script FROM temp_rebuildtables WHERE id = currentRow);
-- select @qry1;
set @start_time=(select CURTIME());
prepare stmt from @qry1 ;
execute stmt ;
-- DO SLEEP(5);
set @end_time=(select CURTIME());
set total_time=TIMEDIFF(@end_time,@start_time);
INSERT INTO `db`.`optimizetable_history` (`table_schema`,`table_name`,`Data_Size`,`DATA_FREE`,`date`,`time_taken`)
select db_name,t_name,Actual_size,free_space,now(),total_time from temp_rebuildtables WHERE id = currentRow;
DO SLEEP(5);
SET currentRow = currentRow+ 1;
END WHILE;
-- select * from `db`.`optimizetable_history` order by date desc ;
drop temporary table if exists temp_rebuildtables;
END$$
DELIMITER ;
Comments
Post a Comment