给定一个表名和列名,如果该列上有索引,则删除。
之所以有这个需求,是因为在做一次sql优化的需求,整理了很多添加索引的sql,但由于某些原因上线延期。后线上出现大量慢sql,无奈根据慢sql手动临时添加几项索引应对。之后再上线此优化需求,此时如果再继续执行以前整理的索引sql,有可能会出现索引重复的问题,因此写出此存储过程解决。
drop procedure if exists delIndexIfExists; create procedure delIndexIfExists(in tablename varchar(30),in columnname varchar(30)) begin declare index_count int; declare the_index_name varchar(50); declare drop_index_sql varchar(300); select count(*) into index_count from information_schema.statistics where TABLE_NAME = tablename and column_name = columnname; while(index_count >0) DO select index_name into the_index_name from information_schema.statistics where TABLE_NAME = tablename and column_name = columnname order by index_name desc limit 1; set @drop_index_sql = concat(' drop index ',the_index_name,' on ',tablename,';'); set index_count = index_count-1; prepare stmt from @drop_index_sql; EXECUTE stmt; end while; END;