不允许从函数返回结果集

时间:2017-10-14 19:45:40

标签: mysql

我正在尝试创建一个函数,该函数返回所有Top Sales的总和,但我收到此错误。

DELIMITER ++

CREATE FUNCTION CostOfBestBuyers(number INT) RETURNS INT
BEGIN 
    SELECT SUM(Tprice)
      FROM (SELECT SUM(T.Quantity * S.ProductPrice) AS Tprice
              FROM Transaction T JOIN Stocks S ON T.ProductCode = S.ProductCode
          GROUP BY UserCode ORDER BY 1 DESC LIMIT number) AS subquery; 
END++

DELIMITER ;

仅SQL语句返回单个值,但是当我将查询放入函数时,它会返回错误。

2 个答案:

答案 0 :(得分:1)

您正在尝试使用无限制SELECT返回结果集,这些函数不支持。您需要返回标量值。要从查询中获取标量值,您需要将其写为标量子查询,并使用RETURN语句返回其值:

DELIMITER ++

CREATE FUNCTION CostOfBestBuyers(number INT) RETURNS INT
BEGIN
  RETURN (
    SELECT SUM(Sum)
      FROM (SELECT SUM(T.Quantity * S.ProductPrice) AS Sum
              FROM Transaction T JOIN Stocks S ON T.ProductCode = S.ProductCode
          GROUP BY UserCode ORDER BY 1 DESC LIMIT number) AS subquery
  ); 
END++

DELIMITER ;

答案 1 :(得分:0)

我认为你只是错过了RETURN

DELIMITER ++

CREATE FUNCTION CostOfBestBuyers(number INT) RETURNS INT
BEGIN 
    RETURN SELECT SUM(Sum)
      FROM (SELECT SUM(T.Quantity * S.ProductPrice) AS Sum
              FROM Transaction T JOIN Stocks S ON T.ProductCode = S.ProductCode
          GROUP BY UserCode ORDER BY 1 DESC LIMIT number) AS subquery; 
END++

DELIMITER ;