0

I have created the following function but seem to be getting an error.

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 ;

I am getting the following error.

#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

I also tried adding ; to the end of the statements but when I do this i get the following error:

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

6

1 Answer 1

1

because you didn't set a value for avg_m_sales
line number 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;

EDIT : another answer

     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;
Sign up to request clarification or add additional context in comments.

8 Comments

You should be able to SELECT directly into the variable, e.g. SELECT avg_m_sales = TRUNCATE((COUNT(paymentdate) / 12),2) FROM sales_table WHERE YEAR(paymentdate) = 2017 AND shopid = shop without the SET and the subquery, I think.
i tried without set and it returns the same error Not allowed to return a result set from a function
@MattGibson At least in MySql the = in SELECT avg_m_sales = .. is a boolean operator. What might work is SELECT .. INTO (avg_m_sales) FROM ...
he has to set return before select if he don't want to use set
@AhmedTaha shop is the variable being passed in and compared to shopid which is from my table.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.