Mysql 存储函数调用存储过程

Mysql Stored Function Call Stored Procedure

我有一个需要为函数调用的存储过程,但是我尝试了以下错误:

Dynamic SQL is not allowed in stored function or trigger

我的函数:

DROP FUNCTION IF EXISTS `clusbe`.`getLongitude`;
CREATE DEFINER=`root`@`localhost` FUNCTION `getLongitude`(`id` INT, `latitude` DOUBLE) RETURNS double
BEGIN
    DECLARE retorno DOUBLE;

    IF (latitude <> '') THEN
      set retorno = latitude;
     ELSE
      CALL proc_getLongitude(1, 0);
     END IF;

  RETURN retorno;
END;

我的存储过程:

DROP PROCEDURE IF EXISTS clusbe.proc_getLongitude;
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_getLongitude`(`id` INT, `longitude` DOUBLE)
BEGIN
    DECLARE retorno DOUBLE;

  IF (longitude <> '' AND longitude <> null) THEN
    set retorno = latitude;
   ELSE
    set @sql =  CONCAT("SELECT longitude FROM endereco as e, usuario as u WHERE e.id = u.endereco AND u.id = ", id);
    PREPARE stmt FROM @sql;    
    EXECUTE stmt ; 
    DEALLOCATE PREPARE stmt;
   END IF;   
END;

有什么想法之类的解决了吗?

正如错误所述,您不能在存储函数中使用动态 SQL,因为您的函数调用 SP 并且 SP 执行动态 SQL。你可以做的替代方法是将动态 SQL 结果存储在临时 table 中,并在你的函数中使用该临时 table 如

set @sql =  CONCAT("CREATE TEMPORARY TABLE table2 AS SELECT longitude FROM endereco as e, usuario as u WHERE e.id = u.endereco AND u.id = ", id);

在您的函数中,从临时 table 获取而不是调用过程

   IF (latitude <> '') THEN
      set retorno = latitude;
     ELSE
      SELECT * FROM table2;
     END IF;