MySQL存储过程,使用游标查找所有错误日期值

时间:2014-11-27 17:32:42

标签: mysql loops stored-procedures cursor

我试图找到我的数据库中的所有条目,其中列的值已创建'不是时间戳。

我编写了一个存储过程,使用游标获取所有已创建'的表格。列。

    DROP PROCEDURE IF EXISTS `findAllErrorDate`;
delimiter //
CREATE PROCEDURE `findAllErrorDate`()
BEGIN
  DECLARE tableNames varchar(100);  
  DECLARE done INTEGER DEFAULT 0;
  DECLARE nameCursor CURSOR FOR SELECT distinct `TABLE_NAME` 
        FROM  `INFORMATION_SCHEMA`.`columns`
        WHERE `COLUMN_NAME` IN ('ID', 'created', 'modified')
        AND `TABLE_SCHEMA` = 'myDB';    
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN nameCursor;
    read_loop: LOOP
        FETCH nameCursor INTO tableNames;
        IF done THEN
        LEAVE read_loop;
        END IF;

        SELECT ID, created, modified 
        FROM tableNames 
        WHERE created not like '20%' 
        AND modified not like '20%';

    END LOOP;
  CLOSE nameCursor;  
END//
delimiter ;

CALL `findAllErrorDate`();

但是我收到了一个错误:

Error Code: 1146. Table 'myDB.tablenames' doesn't exist

有人可以告诉我哪里出错了吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

tableNames是一个变量,您不能将其用作表名,但您可以使用连接字符串中的预准备语句:

SET @sql = CONCAT('SELECT ID, created, modified  FROM ',tableName,
        'WHERE created not like ''20%'' AND modified not like ''20%''');
PREPARE stmt_select FROM @sql;
EXECUTE stmt_select;


DEALLOCATE PREPARE stmt_select;