Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL stored procedure returns wrong values

Im new to MySQL stored procedures and I was following some tutorial on how to use them, but I ran into an interesting thing with the following:

DELIMITER $$
CREATE DEFINER=`user`@`%` PROCEDURE `CalculateScores`(IN ID INT, OUT test INT)
BEGIN
    SELECT COUNT(*)
    INTO test
    FROM myTable
    WHERE id = ID;
END$$
DELIMITER ;

I run it with this:

CALL CalculateScores(252, @test);

and then just:

SELECT @test;

The strange thing is that @test returns the total row count of the entire table not just for the id I sent as a parameter.

What am I missing here? The tutorial never mention this, and I can't find an answer to why this is happening, I might suck at searching..

like image 941
Robin Persson Avatar asked Apr 19 '16 17:04

Robin Persson


People also ask

What is wrong with stored procedures?

Stored procedures are difficult to unit test. With an ORM, you can mock your database code so as to be able to test your business logic quickly. With stored procedures, you have to rebuild an entire test database from scratch. Stored procedures offer no performance advantage whatsoever.

Can mysql stored procedure return value?

To return a value from stored procedure, you need to use user defined session specific variable. Add @ symbol before variable name.

Should stored procedure return value?

Return Value in SQL Server Stored Procedure In default, when we execute a stored procedure in SQL Server, it returns an integer value and this value indicates the execution status of the stored procedure. The 0 value indicates, the procedure is completed successfully and the non-zero values indicate an error.

Which procedure does not return a value?

A Sub procedure does not return a value to the calling code. You call it explicitly with a stand-alone calling statement.


1 Answers

It looks like MySQL cannot differentiate between id and ID:

SELECT COUNT(*)
INTO test
FROM myTable
WHERE id = ID;

And it treats it like 1 = 1 which is always true (if column is not nullable).


You could add alias to indicate that id is column and not parameter.

CREATE PROCEDURE `CalculateScores`(IN ID INT, OUT test INT)
BEGIN
    SELECT COUNT(*)
    INTO test
    FROM myTable t
    WHERE t.id = ID;
END

db<>fiddle demo

like image 129
Lukasz Szozda Avatar answered Sep 28 '22 03:09

Lukasz Szozda