MySQL存储过程无法在Mac OS X上运行

时间:2012-12-10 16:03:45

标签: mysql macos centos

我有以下存储过程(取自http://dev.mysql.com/doc/refman/5.0/en/create-index.html上的注释,用于检查表中是否存在索引):

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 ;

奇怪的是,它在使用MySQL 5.5.25的CentOS 5.4上运行良好,但在Mac OS X 10.8.1和MySQL 5.5.24上不起作用。在Mac上,如果我添加

,则@Index_cnt始终为0
select @Index_cnt

在存储过程中。如果我自己做SELECT COUNT(1) cnt ...语句,那么应该返回1或0。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我重写了存储过程,现在可以在所有平台上运行:

DELIMITER $$

DROP PROCEDURE IF EXISTS myschema.create_index_if_not_exists $$
CREATE PROCEDURE myschema.create_index_if_not_exists(in p_tableName VARCHAR(128), in p_indexName VARCHAR(128), in p_columnName VARCHAR(128) )
BEGIN

PREPARE stmt FROM 'SELECT @indexCount := COUNT(1) from information_schema.statistics WHERE `table_name` = ? AND `index_name` = ?';
SET @table_name = p_tableName;
SET @index_name = p_indexName;
EXECUTE stmt USING @table_name, @index_name;
DEALLOCATE PREPARE stmt;

-- select @indexCount;

IF( @indexCount = 0 ) THEN
  SELECT 'Creating index';
  SET @createIndexStmt = CONCAT('CREATE INDEX ', p_indexName, ' ON ', p_tableName, ' ( ', p_columnName ,')');
  PREPARE stmt FROM @createIndexStmt;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END IF;

END $$

DELIMITER ;

按如下方式使用:

call myschema.create_index_if_not_exists('MyTable','end_time_index','end_time');

这是在使用MySQL 5.5.24的MAC OS X 10.8.2和使用MySQL 5.5.21的Windows 7上测试的