Determining if MySQL table index exists before creating

前端 未结 7 1762
一向
一向 2021-02-04 14:35

Our system\'s automated database migration process involves running .sql scripts containing new table definitions and their accompanying indexes.

I require the ability t

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 15:13

    Since Text and Blobs need a size, I added it to the stored procedure.

    DROP PROCEDURE IF EXISTS createIndex;
    
    DELIMITER $$
    -- Create a temporary stored procedure for checking if Indexes exist before attempting to re-create them. => can be called
    $$
    CREATE PROCEDURE `createIndex`(
        IN `tableName` VARCHAR(128),
        IN `indexName` VARCHAR(128),
        IN `indexColumns` VARCHAR(128),
        IN `indexSize` VARCHAR(128)
    )
    BEGIN
      IF((SELECT COUNT(*) AS index_exists FROM information_schema.statistics WHERE TABLE_SCHEMA = DATABASE() AND table_name = tableName AND index_name = indexName)  = 0) THEN
            IF(indexSize > 0) THEN
                SET @sqlCommand = CONCAT('CREATE INDEX ' , indexName , ' ON ' , tableName, '(', indexColumns, '(' , indexSize, '))');
            ELSE
                SET @sqlCommand = CONCAT('CREATE INDEX ' , indexName , ' ON ' , tableName, '(', indexColumns, ')');
            END IF;
        PREPARE _preparedStatement FROM @sqlCommand;
        EXECUTE _preparedStatement;
      END IF;
    END $$
    DELIMITER ;
    

提交回复
热议问题