Creating a stored function on SQL of average scores, error code 1064

40 views Asked by At

I keep throwing an error code when I try to create a stored funtion for netflix average IMD scores for 3 tables. The code works on it's own but not as a stored function. The answer returns as 7.9999 so I wanted to try to reduce the decimal output in the process to only two decimals, such as 7.9.

CREATE FUNCTION Average_Netflix_Score (
Score INT
) 
RETURNS DECIMAL (2, 2)
DETERMINISTIC
BEGIN 
DECLARE average_score DECIMAL (2, 2);

SELECT AVG(SCORE) INTO average_score
    FROM (
        SELECT SCORE FROM NETFLIX_19
        UNION ALL
        SELECT SCORE FROM NETFLIX_20
        UNION ALL
        SELECT SCORE FROM NETFLIX_21
    ) AS CombinedScores;
    
    RETURN avg_score;
END;

Expected stored function to save with a value of 7.9 as outcome. But got syntax error code 1067.

2

There are 2 answers

1
jarlh On

Note that DECIMAL (2, 2) means a total of 2 digits, of which 2 are decimals, i.e. values like .25.

But you probably want DECIMAL (4, 2), to be able to give values like 12.75.

0
Rahat Mahmud Khan On
CREATE FUNCTION Average_Netflix_Score (
  Score INT
  ) 
  RETURNS DECIMAL (2, 2)
  DETERMINISTIC
  BEGIN 
    DECLARE average_score DECIMAL (2, 2);

    SELECT AVG(SCORE) INTO average_score
    FROM (
      SELECT SCORE FROM NETFLIX_19
      UNION ALL
      SELECT SCORE FROM NETFLIX_20
      UNION ALL
      SELECT SCORE FROM NETFLIX_21
    ) AS CombinedScores;

    RETURN avg_score;
   END;

here shouldn't you RETURN average_score as you declared the average_score but you have returned only avg_score so I think you should change the return avg_score to average_score