首页 > 解决方案 > 带有游标的 MySQL 过程未正常运行

问题描述

我有程序,应该更新一些信息。在表中,但是。它在做。有些这完全错误而不是。更新 . 我的 。桌子

CREATE DEFINER=`andrey.`@`ip` PROCEDURE `sp_visits`()
BEGIN

  DECLARE cursor_VAL VARCHAR(255);
  DECLARE done INT DEFAULT FALSE;
  DECLARE min_date DATETIME DEFAULT FALSE;
  DECLARE max_visits INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT hash_id FROM .ANDREY;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO  cursor_VAL;
    IF done THEN
      LEAVE read_loop;
    END IF;

   select @max_visits := max(visits)
    from ANDREY where hash_id = cursor_VAL ;

    select @min_date :=min(date(transaction_ts)) 
    from ANDREY where hash_id = cursor_VAL and visits =@max_visits;

   update ANDREYt 
   set visits = @max_visits+1
   where hash_id = cursor_VAL  and date(transaction_ts) between date(@min_date) and DATE(@min_date) + INTERVAL 7 DAY;

  END LOOP;
  CLOSE cursor_i;
END

当我从工作台运行它而不是运行它时,它会返回一些记录 # @min_date :=min(date(transaction_ts)) 2018-07-20

我不明白为什么,因为我没有为此过程指定返回,也不明白为什么它不更新我的表,当我手动运行语句时,不在过程逻辑工作,但不在过程中。有任何想法吗?

用这个光标我试图解决这个问题

标签: mysqlsqlcursor

解决方案


当您执行以下操作时:

select @max_visits := max(visits)
from ANDREY where hash_id = cursor_VAL ;

在过程中,此查询的结果作为过程的结果返回。您可以使用以下方法解决它SELECT INTO

SELECT MAX(visits) INTO @max_visits
FROM ANDREY where hash_id = cursor_VAL ;

SELECT MIN(DATE(transaction_ts) INTO @min_date
FROM ANDREY where hash_id = cursor_VAL AND visits = @max_visits;

推荐阅读