Search code examples
mysqlsqlstored-proceduresstored-functions

MySQL CREATE FUNCTION statement seems to ignore WHERE condition


I am writing the first MySQL stored function in my entire life, and I am stuck with something that seems silly even to me with no experience in this.

This is what I wrote until now:

CREATE FUNCTION `credits_per_course`(COURSE_ID INT, USER_ID INT)
RETURNS int(11)
BEGIN

  DECLARE users_credits INT;

  DECLARE course_credits INT;
  DECLARE course_mandatory_credits INT;
  DECLARE course_total_credits INT;

  DECLARE lessons_count INT;

  DECLARE lessons CURSOR FOR
          SELECT * FROM t_lessons WHERE course_id = COURSE_ID;

  SELECT COUNT(*) INTO lessons_count FROM t_lessons WHERE course_id = COURSE_ID;

RETURN lessons_count;
END

I call this using SELECT credits_per_course(1019, 262). The magic numbers are a course of which I know the lessons count and a test user, which at this point of the function is still ignored.

The course 1019 has four lessons. If I run the function, it gives me 2462 lessons, which are the count of ALL the lessons.

For test, I tried to:

  • add a line SET lessons_count = 42; after the SELECT COUNT(*) query and it returns 42;
  • change the WHERE clause using a course id that doesn't exists like 99999 and, correctly, it returns 0 lessons;
  • change the WHERE clause explicitly passing a the 1019 course id but it still giving me 2462 lessons;
  • tried to run outside of the function the SELECT COUNT(*) query with course id of 1019 and it returns 4 lessons.

I know that I am probably making some stupid mistake, but I can't figure out which one...


Solution

  • As JohnHC indicated, that was a problem my ignorance about the case insensitive of parameters name.

    So, once changed the name of the parameter to something like CID and UID, it worked properly.

    Thanks!