1

我有以下存储过程,旨在实现 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表已正确存储在数据库中,并且其中的所有点 idpids也在sampledata表中。另外,这个 EXACT 代码适用于另一个过程,但在这里重用它是行不通的。

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

4

1 回答 1

0

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

于 2012-12-18T13:34:38.527 回答