如何使删除索引,如果存在的MySQL?

n9vozmp4  于 2023-01-20  发布在  Mysql
关注(0)|答案(2)|浏览(324)

我想在MySQL中删除索引选项,如果存在,但我没有找到任何使它工作。

DROP INDEX IF EXISTS index_name ON table_name;

有人有什么提示吗?

pbossiut

pbossiut1#

我没有看到任何直接使用IF EXISTSDROP INDEX方法。作为一种变通方法,我编写了下面的过程,它对我很有效。

CREATE PROCEDURE `DropIndexIfExists`(
    IN i_table_name VARCHAR(128),
    IN i_index_name VARCHAR(128)
    )
    BEGIN

    SET @tableName = i_table_name;
    SET @indexName = i_index_name;
    SET @indexExists = 0;

    SELECT 
        1
    INTO @indexExists FROM
        INFORMATION_SCHEMA.STATISTICS
    WHERE
        TABLE_NAME = @tableName
            AND INDEX_NAME = @indexName;

    SET @query = CONCAT(
        'DROP INDEX ', @indexName, ' ON ', @tableName
    );
    IF @indexExists THEN
        PREPARE stmt FROM @query;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;
    END
g52tjvyc

g52tjvyc2#

试试这个

create procedure DeleteIndex()
begin

IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.STATISTICS  WHERE TABLE_NAME = 'TableName'
            AND INDEX_NAME = 'IndexName' AND INDEX_SCHEMA='DbName') THEN
   ALTER TABLE  TableName DROP index THead2;
END IF;
END

相关问题