在mysql过程循环中处理未找到的数据

wgxvkvu9  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(247)

我想我正在缩小我的范围。我有一个循环只发射一次:

DELIMITER $$

DROP PROCEDURE IF EXISTS `thread_updates` $$
CREATE PROCEDURE `thread_updates`()
BEGIN

DECLARE done INT DEFAULT 0;
DECLARE my_curr_id INT DEFAULT NULL;
-- DECLARE other vars
DECLARE fixer_cursor CURSOR FOR
  SELECT DISTINCT(id)
  FROM log
  WHERE date >= '2018-01-01';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN fixer_cursor;
REPEAT
  FETCH fixer_cursor INTO my_curr_id;
  IF NOT done THEN
    SELECT data FROM table WHERE id = my_curr_id; -- This may not exist 
    -- Do other stuff with 'data' or NULL from above
  END IF;
UNTIL done END REPEAT;
CLOSE fixer_cursor;
END $$
DELIMITER ;

我认为问题可能出在 IF NOT done THEN 循环中,我有几个select语句可能试图选择不存在(未找到)的结果。
对于我来说,这很好,因为逻辑继续在这些点中使用空值,但是我怀疑 CONTINUE HANDLER FOR NOT FOUND 正在抓到 NOT FOUND 警告这些选择将抛出循环内部,从而过早地停止整个循环。
我怎么能听你的 NOT FOUND 仅对我的光标发出警告?
或者,我怎样才能抑制 NOT FOUND 我的循环中的警告可能在我的循环中发现select语句,所以我的循环继续?

lrl1mhuk

lrl1mhuk1#

我认为通过在循环中实现计数器而不是依赖 NOT FOUND 经办人:

DELIMITER $$

DROP PROCEDURE IF EXISTS `thread_updates` $$
CREATE PROCEDURE `thread_updates`()
BEGIN

DECLARE my_total INT DEFAULT NULL; -- Declare total
DECLARE my_counter INT DEFAULT 0; -- Declare counter starting at 0
DECLARE my_curr_id INT DEFAULT NULL;
-- DECLARE other vars
DECLARE fixer_cursor CURSOR FOR
  SELECT DISTINCT(id)
  FROM log
  WHERE date >= '2018-01-01';

OPEN fixer_cursor;

SELECT FOUND_ROWS() INTO my_total; -- Get total number of rows

my_fixerloop: LOOP

  FETCH fixer_cursor INTO my_curr_id;
  IF my_counter >= my_total THEN -- Compare counter to total
    CLOSE fixer_cursor;
    LEAVE my_fixerloop;
  END IF;

  SET my_counter = my_counter + 1; -- Increment by one for each record

  SELECT data FROM table WHERE id = my_curr_id; -- This may not exist 
  -- Do other stuff with 'data' or NULL from above

END LOOP;
END $$
DELIMITER ;

相关问题