欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MySQL中判断索引不存在时添加索引

程序员文章站 2022-05-08 18:33:44
...
使用存储过程实现索引添加:
DROP PROCEDURE IF EXISTS add_index;

CREATE PROCEDURE add_index()
  BEGIN
    DECLARE  CurrentDatabase VARCHAR(100);
    SELECT DATABASE() INTO CurrentDatabase;
    IF NOT EXISTS (SELECT * FROM information_schema.statistics WHERE table_schema=CurrentDatabase AND table_name = 'tbl03' AND index_name = 'start_idx') THE
N
    ALTER TABLE tbl03 ADD INDEX start_idx (start);
    END IF;
    IF NOT EXISTS (SELECT * FROM information_schema.statistics WHERE table_schema=CurrentDatabase AND table_name = 'tbl03' AND index_name = 'stop_idx') THEN
    ALTER TABLE tbl03 ADD INDEX stop_idx (stop);
    END IF;
END



调用和删除存储过程
CALL add_index();
DROP PROCEDURE IF EXISTS add_index;