MySQL存储来自SELECT语句的过程变量

时间:2012-05-18 09:07:49

标签: mysql stored-procedures

我正在尝试创建存储过程。这是我到目前为止(不工作):

DELIMITER |
CREATE PROCEDURE getNearestCities(IN cityID INT)
    BEGIN
        DECLARE cityLat FLOAT;
        DECLARE cityLng FLOAT;
        SET cityLat = SELECT cities.lat FROM cities WHERE cities.id = cityID;
        SET cityLng = SELECT cities.lng FROM cities WHERE cities.id = cityID;
        SELECT *, HAVERSINE(cityLat,cityLng, cities.lat, cities.lng) AS dist FROM cities ORDER BY dist LIMIT 10;
    END |

HAVERSINE是我创建的一个功能很好的功能。正如您所看到的,我正在尝试从cities表中获取城市的id,然后将cityLat和cityLng设置为该记录的其他值。我在这里使用SELECTs显然做错了。

这是否可能。它似乎应该是。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:16)

您只需要将SELECT语句括在括号中以表明它们是子查询:

SET cityLat = (SELECT cities.lat FROM cities WHERE cities.id = cityID);

或者,您可以使用MySQL的SELECT ... INTO语法。这种方法的一个优点是可以从单个表访问分配cityLatcityLng

SELECT lat, lng INTO cityLat, cityLng FROM cities WHERE id = cityID;

但是,整个过程可以用一个自联接的SELECT语句替换:

SELECT   b.*, HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM     cities AS a, cities AS b
WHERE    a.id = cityID
ORDER BY dist
LIMIT    10;

答案 1 :(得分:15)

纠正了一些问题,并添加了另一种选择 - 适当删除。

DELIMITER |

CREATE PROCEDURE getNearestCities
(
IN p_cityID INT -- should this be int unsigned ?
)
BEGIN

DECLARE cityLat FLOAT; -- should these be decimals ?
DECLARE cityLng FLOAT;

    -- method 1
    SELECT lat,lng into cityLat, cityLng FROM cities WHERE cities.cityID = p_cityID;

    SELECT 
     b.*, 
     HAVERSINE(cityLat,cityLng, b.lat, b.lng) AS dist 
    FROM 
     cities b 
    ORDER BY 
     dist 
    LIMIT 10;

    -- method 2
    SELECT   
      b.*, 
      HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
    FROM     
      cities AS a
    JOIN cities AS b on a.cityID = p_cityID
    ORDER BY 
      dist
    LIMIT 10;

END |

delimiter ;

答案 2 :(得分:0)

我正面临一种奇怪的行为。

SELECT INTO和SET都适用于某些变量,而不适用于其他变量。事件语法相同

SET @Invoice_UserId :=  (SELECT UserId FROM invoice WHERE InvoiceId = @Invoice_Id  LIMIT 1); -- Working
                SET @myamount := (SELECT amount FROM invoice WHERE InvoiceId = @Invoice_Id LIMIT 1); - Not working
SELECT  Amount INTO @myamount FROM invoice WHERE InvoiceId = 29  LIMIT 1; - Not working

如果我直接运行这些查询,则可以,但是不能在存储过程中使用。