如何将MySQL存储过程与变量一起使用?

时间:2010-06-15 21:20:38

标签: mysql stored-procedures

我找到了一个存储过程,用于计算点是在多边形中还是在多边形之外。但是,我在适应我的需求方面遇到了一些麻烦。

存储过程调用如下:

SET @point = PointFromText('POINT(5 5)') ;
SET @polygon = PolyFromText('POLYGON((0 0, 0 10, 10 10, 10 0, 0 0))');
SELECT myWithin(@point, @polygon) AS result; 

我想从myPointsTable中拉出纬度和经度,并将@point设置为结果。像(伪代码):

    SET @point = PointFromText('POINT( SELECT latitude, longitude
    FROM `myPointsTable` 
    WHERE  color = 'red')') ;

然后让存储过程迭代这些点。

同样,我想从myPolygonTable中拉出多边形。像(伪代码):

SET @polygon = PolyFromText('POLYGON((SELECT polygonPoints FROM 'myPolygonTable' WHERE town = 'Newport'))');

存储过程是:

DROP FUNCTION IF EXISTS myWithin;
DELIMITER $$
CREATE FUNCTION myWithin(p POINT, poly POLYGON) RETURNS INT(1) DETERMINISTIC
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE pX DECIMAL(9,6);
DECLARE pY DECIMAL(9,6);
DECLARE ls LINESTRING;
DECLARE poly1 POINT;
DECLARE poly1X DECIMAL(9,6);
DECLARE poly1Y DECIMAL(9,6);
DECLARE poly2 POINT;
DECLARE poly2X DECIMAL(9,6);
DECLARE poly2Y DECIMAL(9,6);
DECLARE i INT DEFAULT 0;
DECLARE result INT(1) DEFAULT 0;
SET pX = X(p);
SET pY = Y(p);
SET ls = ExteriorRing(poly);
SET poly2 = EndPoint(ls);
SET poly2X = X(poly2);
SET poly2Y = Y(poly2);
SET n = NumPoints(ls);
WHILE i<n DO
SET poly1 = PointN(ls, (i+1));
SET poly1X = X(poly1);
SET poly1Y = Y(poly1);
IF ( ( ( ( poly1X <= pX ) 
&& ( pX < poly2X ) ) || ( ( poly2X <= pX ) 
&& ( pX < poly1X ) ) ) 
&& ( pY > ( poly2Y - poly1Y ) * ( pX - poly1X ) / ( poly2X - poly1X ) + poly1Y ) ) THEN
SET result = !result;
END IF;
SET poly2X = poly1X;
SET poly2Y = poly1Y;
SET i = i + 1;
END WHILE;
RETURN result;
End
$$
DELIMITER ;

如何在设置变量时使用SELECT语句?可能吗?还有更好的方法吗?

谢谢。

-Laxmidi

更新:

您好,

我已经解决了部分问题。我已经想出如何抓住纬度和经度。

DROP PROCEDURE IF EXISTS latlongGrabber;
DELIMITER $$
CREATE PROCEDURE latlongGrabber(IN offense_in VARCHAR(255))

BEGIN
     DECLARE latitude_val VARCHAR(255);
     DECLARE longitude_val VARCHAR(255);
     DECLARE no_more_rows BOOLEAN;
     DECLARE latlongGrabber_cur CURSOR FOR

     SELECT latitude, longitude FROM myTable WHERE offense = offense_in;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = TRUE;

OPEN latlongGrabber_cur;


the_loop: LOOP

FETCH latlongGrabber_cur
INTO latitude_val, longitude_val;

IF no_more_rows THEN CLOSE latlongGrabber_cur;
LEAVE the_loop;
END IF;
SELECT latitude_val, longitude_val;
END LOOP the_loop;
END
$$
DELIMITER ;

现在,我必须弄清楚如何组合这两个功能。

-Laxmidi

1 个答案:

答案 0 :(得分:1)

SELECT INTO语句允许您选择变量。这就是你追求的吗?见这里:

http://dev.mysql.com/doc/refman/5.0/en/select-into-statement.html

SELECT col_name [, col_name] ...
    INTO var_name [, var_name] ...
    table_expr