Reputation: 11228
Trying to figure out why it is NULL. I was expecting 7 to be printed.
mysql> set @total = 0;
Query OK, 0 rows affected (0.00 sec)
mysql> call getAuthorCount(@total);
+------------------------+
| count(distinct author) |
+------------------------+
| 7 |
+------------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.02 sec)
mysql> select @total as totalauthors;
+--------------+
| totalauthors |
+--------------+
| NULL |
+--------------+
The procedure,
mysql> create procedure getAuthorCount(out authorcount int)
-> begin
-> select count(distinct author) from libbooks;
-> end
-> //
Upvotes: 0
Views: 178
Reputation: 121922
You should use INOUT parameter -
CREATE PROCEDURE getAuthorCount(INOUT authorcount INT)
BEGIN
SELECT count(DISTINCT author) FROM libbooks;
END
Examples:
When @total value is as is (0 in, 0 out):
DROP PROCEDURE getAuthorCount;
DELIMITER $$
CREATE PROCEDURE getAuthorCount(INOUT authorcount INT)
BEGIN
-- SET authorcount = 100;
END$$
DELIMITER ;
SET @total = 0;
CALL getAuthorCount(@total);
SELECT @total AS totalauthors;
+--------------+
| totalauthors |
+--------------+
| 0 |
+--------------+
When @total value is replaces with a new value in stored procedure:
DROP PROCEDURE getAuthorCount;
DELIMITER $$
CREATE PROCEDURE getAuthorCount(OUT authorcount INT)
BEGIN
SET authorcount = 100;
END$$
DELIMITER ;
SET @total = 0;
CALL getAuthorCount(@total);
SELECT @total AS totalauthors;
+--------------+
| totalauthors |
+--------------+
| 100 |
+--------------+
Upvotes: 2