How to make DROP INDEX IF EXISTS for mysql?

I want DROP INDEX in mysql with the IF EXISTS option, but I did not find anything that would make it work.

DROP INDEX IF EXISTS index_name ON table_name;

Does anyone have a clue?

+4
source share
3 answers

I do not see a direct path to DROP INDEXusing IF EXISTS. As a workaround, I wrote the following procedure, which works for me.

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
+1
source

Try it,

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
+1
source

I used this and it worked for me.

ALTER TABLE 'db_name'.'table_name' DROP INDEX IF EXISTS 'index_name'
0
source

Source: https://habr.com/ru/post/1656675/


All Articles