MYSQL Function "Error Code: 1242 subquery returns more than 1 row" but I have no subqueries

GrayFullBuster picture GrayFullBuster · Nov 28, 2012 · Viewed 15.7k times · Source

I don't know what is the problem why it gives me error in running the function

Here is my sql:

    CREATE FUNCTION `test`.`GetProcessorMethodID` (processor_id INT, method_id INT)
RETURNS INTEGER
BEGIN
    DECLARE id INT;
    SET @id := (SELECT `processor_method_id` FROM `processor_method` WHERE `processor_id` = processor_id AND `method_id` = method_id);
RETURN @id;
END

enter image description here

But when I use this line of sql

    SELECT processor_method_id FROM test.processor_method
WHERE processor_id = 1 AND method_id = 2;

enter image description here

It works fine!. It gives but the expected value I want to get. But in my function it does not return my expected values and always gives me error and I don't know what is wrong

Answer

DRapp picture DRapp · Nov 28, 2012

Your problem is actually quite simple and you'll DEFINITELY remember it in the future... Change your parameter names... from processor_id, method_id to something like parmProcessor, parmMethod

AS IT Stands, your current parameters are the exact same name as the column names you are querying for, and thus

where `processor_id` = processor_id (same with method)

are BOTH referring to actual column name, and 1=1 all day long and 2=2 the same, so you are getting every record.

By changing them to something slightly different as sampled above you would get

where `processor_id` = parmProcessor and `method_id` = parmMethod

which is an EXPLICITLY DIFFERENT implication in the query.