简体   繁体   English

MySQL CREATE FUNCTION语句似乎忽略了WHERE条件

[英]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. 我正在写一生中的第一个MySQL存储函数,即使没有经验,我仍然觉得有些愚蠢。

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) . 我用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. 课程1019有四节课。 If I run the function, it gives me 2462 lessons, which are the count of ALL the lessons. 如果运行该函数,它将给我2462课,这是所有课的总数。

For test, I tried to: 为了进行测试,我尝试:

  • add a line SET lessons_count = 42; 添加一行SET lessons_count = 42; after the SELECT COUNT(*) query and it returns 42; SELECT COUNT(*)查询之后,它返回42;
  • change the WHERE clause using a course id that doesn't exists like 99999 and, correctly, it returns 0 lessons; 使用不存在的课程ID(如99999)更改WHERE子句,正确地,它返回0课;
  • change the WHERE clause explicitly passing a the 1019 course id but it still giving me 2462 lessons; 更改WHERE子句,以显式传递1019课程ID,但它仍为我提供2462课;
  • tried to run outside of the function the SELECT COUNT(*) query with course id of 1019 and it returns 4 lessons. 尝试在功能SELECT COUNT(*)查询的函数之外运行,课程ID为1019,它返回4节课。

I know that I am probably making some stupid mistake, but I can't figure out which one... 我知道我可能犯了一些愚蠢的错误,但我不知道是哪一个...

As JohnHC indicated, that was a problem my ignorance about the case insensitive of parameters name. 正如JohnHC指出的那样,这是我对参数名称不区分大小写的无知。

So, once changed the name of the parameter to something like CID and UID , it worked properly. 因此,将参数名称更改为CIDUID类的名称后,它便可以正常工作。

Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM