I have the following stored procedure (Taken from a comment on http://dev.mysql.com/doc/refman/5.0/en/create-index.html, used to check if an index exists on a table):
DELIMITER $$
DROP PROCEDURE IF EXISTS `create_index_if_not_exists`$$
CREATE DEFINER=`user`@`%` PROCEDURE `create_index_if_not_exists`(table_name_vc varchar(50), index_name_vc varchar(50), field_list_vc varchar(200))
SQL SECURITY INVOKER
BEGIN
set @Index_cnt = (
select count(1) cnt
FROM INFORMATION_SCHEMA.STATISTICS
WHERE table_name = table_name_vc
and index_name = index_name_vc
);
IF ifnull(@Index_cnt,0) = 0 THEN set @index_sql = concat('Alter table ',table_name_vc,' ADD INDEX ',index_name_vc,'(',field_list_vc,');');
PREPARE stmt FROM @index_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END$$
DELIMITER ;
The strange thing is that it works perfectly on CentOS 5.4 with MySQL 5.5.25, but does not work on Mac OS X 10.8.1 with MySQL 5.5.24. On Mac, the @Index_cnt is always 0 if I add
select @Index_cnt
in the stored procedure. If I do the SELECT COUNT(1) cnt ... statement on it’s own, then 1 or 0 is returned as it should be.
Any ideas?
I have re-written the stored procedure and this now works on all platforms:
Use it as follows:
This was tested on MAC OS X 10.8.2 with MySQL 5.5.24 and on Windows 7 with MySQL 5.5.21