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..
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.
To return a value from stored procedure, you need to use user defined session specific variable. Add @ symbol before variable name.
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.
A Sub procedure does not return a value to the calling code. You call it explicitly with a stand-alone calling statement.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With