MySQL Cursor Fetch无法正常工作

时间:2012-12-18 00:36:55

标签: mysql stored-procedures

我有以下存储过程,用于实现Dijkstra的最短路径算法:

CREATE PROCEDURE `Dijkstras`(IN `pids` VARCHAR(512), IN `startP` VARCHAR(8), IN `endP` VARCHAR(8), OUT `dist` DECIMAL(20,10), OUT `eset` VARCHAR(1024))
BEGIN
DECLARE currentP VARCHAR(4);
DECLARE finished INT DEFAULT 0;
DECLARE pt_from, pt_to int;
DECLARE pt_dist decimal(20,10);
DECLARE done INT DEFAULT 0;

DECLARE cur2 CURSOR FOR 
    select F.id as `from`, T.id as `to`, dist(F.lat, F.lng, T.lat, T.lng) 
      as dist
    from   sampledata F, sampledata T
    where  F.id < T.id and 
           find_in_set(convert(F.id, char(10)), pids) and
           find_in_set(convert(T.id, char(10)), pids) 
    order by dist;
  DECLARE CONTINUE HANDLER FOR not found SET done = 1; 

    SET currentP= startP;
  SET eset = '';
  SET dist = 0;


  SET done=0;
  OPEN cur2; -- this finds pariwise distances in miles.
  REPEAT 
    FETCH cur2 INTO pt_from, pt_to, pt_dist; 
    SET dist= dist+pt_dist;
        SET eset= CONCAT(eset, ',');
    IF(currentP=pt_from OR currentP=pt_to) AND 
    (IN_SET(pt_from,pids) AND IN_SET(pt_to,pids))  THEN
        BEGIN
            SET dist= dist+ pt_dist;
            SET pids= REMOVE_MEMBER(currentP, pids);
            SET eset = concat(eset, ',', concat(pt_from, ':', pt_to));
                IF left(eset, 1) = ',' then 
                    SET eset = substring(eset, 2); -- remove extra comma.
                END IF;
            IF currentP=pt_from THEN
                SET currentP=pt_to;
            ELSE 
                SET currentP=pt_from; 
            END IF;
            IF currentP= endP THEN
            SET finished= 1;
            END IF;
     END;
      END IF;
         UNTIL done 

  END REPEAT; 
  CLOSE cur2;


END

我的问题是光标无法正常工作。当我将当前行提取到pt_from, pt_to,pt_dist时,我得到的是NULL值。 sampledata表正确存储在数据库中,pids中的所有点ID也都在sampledata表中。此外,这个EXACT代码适用于另一个程序,但在此重复使用它是行不通的。

有人知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

错误是我传递了像这个'12, 15, 18'的点ID,其间有空格。 MySQL在解析字符串时计算空白,并且列表中的id没有空格。传递字符串集的正确方法是'12,15,18'