且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从存储过程创建索引或在MySQL中的每个表上创建索引?

更新时间:2023-02-15 10:12:44

核心问题您的过程是 PREPARE 语句仅适用于用户变量或字符串文字。它无法从过程变量中准备语句。

The core problem with your procedure was that PREPARE statement only works with a user variable or a string literal. It can't prepare a statement from a procedure variable.


PREPARE语法

PREPARE stmt_name FROM preparable_stmt

... preparable_stmt是字符串文字或用户变量
包含SQL语句的文本。

PREPARE Syntax
PREPARE stmt_name FROM preparable_stmt
... preparable_stmt is either a string literal or a user variable that contains the text of the SQL statement.



DELIMITER //
CREATE PROCEDURE createModifiedIndex(t VARCHAR(256))
  BEGIN
    DECLARE idx VARCHAR(256);
    DECLARE i INT;

    SET idx = CONCAT('idx_', t, '_modified_on');
    SET i = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS WHERE table_name = t AND index_name = idx);
    IF i = 0 THEN
        SET @makeIndexSql = CONCAT('CREATE INDEX ', idx, ' ON ', t, ' (modified_on);');
        PREPARE stmt FROM @makeIndexSql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt; -- Use DEALLOCATE when you're done with the statement
    END IF;
  END //

DELIMITER ;