MySQL存储过程,如果存储过程的结果集为空,则更改一个变量并再次运行

标签 mysql sql stored-procedures

我有一个存储过程:

DROP PROCEDURE `getCercanoRadio`//
CREATE DEFINER=`prog2sc`@`localhost` 
PROCEDURE `getCercanoRadio`
  (IN latitude Double, IN longitude Double, IN tipo_servicio INT)
BEGIN
    SET @LAT = latitude;
    SET @LON = longitude;
    SET @Servicio = tipo_servicio;
    SET @point = CONCAT('POINT(',@LAT,' ',@LON,')');
    SET @center = GeomFromText(@point); 
    SET @radius = 0.01; 
    SET @bbox = CONCAT('POLYGON((', 
    X(@center) - @radius, ' ', Y(@center) - @radius, ',', 
    X(@center) + @radius, ' ', Y(@center) - @radius, ',', 
    X(@center) + @radius, ' ', Y(@center) + @radius, ',', 
    X(@center) - @radius, ' ', Y(@center) + @radius, ',', 
    X(@center) - @radius, ' ', Y(@center) - @radius, '))'); 

    SELECT
      prog2sc_SCDBs.Punto_Geografico.latitude
      ,prog2sc_SCDBs.Punto_Geografico.longitude
      , prog2sc_SCDBs.Tipo_Servicio.idTipo_Servicio
      , prog2sc_SCDBs.Ubicacion.nombreUbicacion
      , SQRT(POW( ABS( X(geopoint) - X(@center)), 2) 
        + POW( ABS(Y(geopoint) - Y(@center)), 2 )) AS distance 
    FROM prog2sc_SCDBs.Ubicacion 
    INNER JOIN prog2sc_SCDBs.Tipo_Servicio ON
      prog2sc_SCDBs.Ubicacion.Tipo_Servicio_idTipo_Servicio = idTipo_Servicio
    INNER JOIN prog2sc_SCDBs.Punto_Geografico ON 
      prog2sc_SCDBs.Ubicacion.idUbicacion =  
        prog2sc_SCDBs.Punto_Geografico.idPunto_Geografico
    WHERE Intersects( geopoint, GeomFromText(@bbox) )
    AND idTipo_Servicio=@Servicio
    AND (
      SQRT(POW( ABS( X(geopoint) - X(@center)), 2) 
      + POW( ABS(Y(geopoint) - Y(@center)), 2 ))
         ) < @radius 
    ORDER BY distance,geopoint;
  END

我想进行条件检查,如果此存储过程的结果集为空,则增加@radius并再次运行,直到结果集不为空。

最佳答案

为了继续运行该语句直到获得特定结果,您需要 LOOP statement 。此外,您不应只运行 SELECT,而是应向语句 ( example here ) 添加一个 INTO 子句来临时存储查询结果。您需要 define the variables first - 在您的情况下,变量可能是 @latitude@longitude 等,它们的定义应与列中的数据类型相对应。

运行SELECT ... INTO ...后,您可以test the contents of the variables ,如果这不是您想要的,请增加您的 @radius 并允许循环继续,否则,发出 LEAVE 结束循环。

要从过程中返回数据,您可以使用 OUT 参数(如 CREATE PROCEDURE manpage 中所述),也可以发出另一个 SELECT

OUT 参数意味着更改过程的参数(将 OUT 类型参数添加到 IN 参数列表中),并且其调用方式不同,因为 OUT 参数的处理方式与过程中 SELECT 的结果不同。

使用SELECT 方法,您可以为过程末尾定义的变量发出SELECT。使用此方法,数据将以您当前的格式显示。您可以在 LOOP 之后执行类似的操作:

SELECT @latitude, @longitude, ... ;

该方法意味着调用该过程的现有代码不需要更改 - 只要您为变量添加别名以匹配现有查询的列名称即可。

关于MySQL存储过程,如果存储过程的结果集为空,则更改一个变量并再次运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5760465/

相关文章:

mysql - 显示存在值的表名

c# - 如何在 Entity Framework 中运行存储过程

mysql 存储过程输出文件

php - 按钮操作在android v9 +上无法正常工作,但在v4-8上有效

mysql - 将数据从旧模式迁移到新模式

sql - 在 MS Access 和 SQL Server 中处理图片

sql - JPA无锁读取数据

MYSQL 函数/过程

php - ?使用表中的 COUNT 和具有相关数据的另一个表中的 SUM

mysql - 用于计算总和的存储过程 - MySQL 5