Determining if MySQL table index exists before creating

前端 未结 7 1851
一向
一向 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:19

    Not a new version but a more complete solution that includes a call to create 2 indexes.

    USE MyDatabaseName;
    DELIMITER $$
    -- Create a temporary stored procedure for checking if Indexes exist before attempting to re-create them.
    DROP PROCEDURE IF EXISTS `MyDatabaseName`.`spCreateIndex` $$
    CREATE PROCEDURE `MyDatabaseName`.`spCreateIndex` (tableName VARCHAR(128), in indexName VARCHAR(128), in indexColumns 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
        SET @sqlCommand = CONCAT('CREATE INDEX ' , indexName , ' ON ' , tableName, '(', indexColumns, ')');
        PREPARE _preparedStatement FROM @sqlCommand;
        EXECUTE _preparedStatement;
      END IF;
    END $$
    DELIMITER ;
    
    -- Create the Indexes if they do not exist already.
    CALL spCreateIndex('MyCustomers', 'idxCustNum', 'CustomerNumber');
    CALL spCreateIndex('MyProducts', 'idxProductName', 'ProductName');
    
    DELIMITER $$
    -- Drop the temporary stored procedure.
    DROP PROCEDURE IF EXISTS `MyDatabaseName`.`spCreateIndex` $$
    DELIMITER ;
    

提交回复
热议问题