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

标签 mysql sql stored-procedures indexing

这是我迄今为止尝试过的两件事,以及它们的错误消息:

DELIMITER //

CREATE PROCEDURE createModifiedIndex(t varchar(256))
  BEGIN
    declare idx varchar(256);
    DECLARE i int;
    declare makeIndexSql varchar(256);
    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;
    end if;
  END //

DELIMITER ;

call createModifiedIndex ('ACHDebitFrequencies');
call createModifiedIndex ...

ERROR 1064 (42000) at line 5: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'makeIndexSql; execute stmt; end if; END' at line 10

这是另一种不同的尝试,但不会奏效,因为 MySQL 不允许在存储过程之外使用 IF/THEN。

set @i = (select count(*) from INFORMATION_SCHEMA.STATISTICS where table_name = 'ACHDebitFrequencies' and index_name = 'idx_ACHDebitFrequencies_modified_on');
if @i > 0 then begin
        create index 'idx_ACHDebitFrequencies_modified_on' on ACHDebitFrequencies (modified_on);
end;
end if;
...

ERROR 1064 (42000) at line 3: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'if @i > 0 then begin create index 'idx_ACHDebitFrequencies_modified_on' on ACHD' at line 1

版本 mysql-5.1.62-r1

最佳答案

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

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 ;

关于mysql - 如何从存储过程创建索引或在 MySQL 中的每个表上创建索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17246078/

相关文章:

mysql - 如何向我的查询添加日期条件?

mysql - MySQL 每 1 天执行一次存储过程

php - 提交SQL查询时是否需要验证列名?

mysql - 用mysql统计第一名分数的个数

sql - 如何根据特定字段中的数据向查询添加行

mysql - 使用光标查找表中的值

Mysql存储过程

java - hibernate 条件 : NOW() < date + 1 day

mysql - 如何在mysql中循环创建一个create table语句

php - 如何使用 AES_ENCRYPT 和 PDO 准备语句改进 PHP 中大型加密数据库的解决方法?