我有以下存储过程,用于实现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代码可用于其他过程,但在此处无法重复使用。

有人知道我在做什么错吗?

最佳答案

错误是我传入了点这样的点ID,中间是空格。 MySQL在解析字符串时会计算空格,并且表中的ID不含空格。传递字符串集的正确方法是'12, 15, 18'

10-04 21:35
查看更多