MySQL - MySQL用户定义函数的正确语法

时间:2017-11-24 21:04:24

标签: mysql sql

我创建了以下函数,但似乎收到错误。

DELIMITER $$
CREATE FUNCTION avg_month(shop INTEGER) RETURNS DECIMAL
BEGIN
  DECLARE
    avg_m_sales DECIMAL
  SELECT TRUNCATE((COUNT(paymentdate) / 12),2) FROM sales_table 
  WHERE YEAR(paymentdate) = 2017 AND shopid = shop
RETURN avg_m_sales
END $$
DELIMITER ;

我收到以下错误。

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT TRUNCATE((COUNT(payid) / 12),2) FROM fss_Payment WHERE YEAR(paydate) ' at line 5

我还尝试将;添加到语句的末尾,但是当我这样做时,我收到以下错误:

#1415 - Not allowed to return a result set from a function

1 个答案:

答案 0 :(得分:1)

因为您没有为avg_m_sales设置值 第4行

     CREATE FUNCTION avg_month(shop INTEGER) RETURNS DECIMAL 
     BEGIN 
       DECLARE avg_m_sales DECIMAL;
         SET avg_m_sales=(
         SELECT TRUNCATE((COUNT(paymentdate) / 12),2) FROM sales_table
         WHERE YEAR(paymentdate) = 2017 AND shopid = shop);
       RETURN avg_m_sales;
     END;

编辑:另一个答案

     CREATE FUNCTION avg_month(shop INTEGER) RETURNS DECIMAL 
     BEGIN 
         RETURN (SELECT TRUNCATE((COUNT(paymentdate) / 12),2) FROM sales_table
         WHERE YEAR(paymentdate) = 2017 AND shopid = shop);
     END;