MySQL过程机智游标无法正常运行

时间:2018-07-26 00:36:09

标签: mysql sql cursor

我有可能要更新一些信息的程序。在桌子上,但是。它正在做。这完全是错误的,不是。更新。我的。表格

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

我没搞错为什么,因为我没有为该过程指定返回值,也不理解为什么当我手动运行不在过程逻辑中但不在过程中的语句时,为什么它不更新我的表。有任何想法吗?

with this cursor i am trying to resolve this problem

1 个答案:

答案 0 :(得分:1)

当您执行以下操作时:

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;