Home  >  Article  >  Database  >  mysql判断索引存在时删除索引的方法_MySQL

mysql判断索引存在时删除索引的方法_MySQL

WBOY
WBOYOriginal
2016-06-01 13:36:043297browse

bitsCN.com

mysql判断索引存在时删除索引的方法

 

mysql的drop index语句不支持if exists条件,在sql中先删除索引,

再创建索引,如果对于新建的数据库,库中没有该索引,就会报错,

导致后面的sql不再执行。

因此需要使用存储过程来判断索引是否存在,如果存在则删除。

sql代码如下:

 

Sql代码  

DROP PROCEDURE IF EXISTS del_idx;  

create procedure del_idx(IN p_tablename varchar(200), IN p_idxname VARCHAR(200))  

begin  

DECLARE str VARCHAR(250);  

  set @str=concat(' drop index ',p_idxname,' on ',p_tablename);   

    

  select count(*) into @cnt from information_schema.statistics where table_name=p_tablename and index_name=p_idxname ;  

  if @cnt >0 then   

    PREPARE stmt FROM @str;  

    EXECUTE stmt ;  

  end if;  

  

end ;  

call del_idx('table_name','index_name');  

ALTER TABLE table_name ADD INDEX index_name (column1, column2);

 

bitsCN.com
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn