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

bd96500e110b49cbb3cd949968f18be7.png

These are two things that I've tried so far, along with their error messages:

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

This is another different attempt but won't work because MySQL doesn't allow IF/THEN outside of stored procedures.

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

Version mysql-5.1.62-r1

解决方案

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.

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 ;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值