Even better solution is to create the temporary table outside of the stored procedure, and have the procedure just update/insert to it. This way results of multiple calls can be stored in one table (as long as there are the same columns inserted), and retrieved in the end with a simple SELECT
.
Here is an example using the same data as #sinecospi above:
/* The data */
drop table if exists someData ;
create table someData (itemId int, itemName varchar(20), itemQty int, itemCat int) ;
insert into someData values
(1,'First', 9, 1)
,(2,'Second',50, 3)
,(3,'Third', 12, 5)
,(4,'Fourth', 7, 3)
,(5,'Fifth', 1, 2)
,(6,'Sixth', 1, 1)
,(7,'Seventh', 9, 3)
,(8,'Eighth', 0, 2);
/* The stored procedure */
DROP PROCEDURE IF EXISTS sproc;
DELIMITER //
CREATE PROCEDURE sproc(
IN fld CHAR(64),
IN tbl CHAR(64)
)
BEGIN
SET @s = CONCAT('INSERT INTO results
SELECT \'',fld,'\' AS fld, x.* FROM (
SELECT ',fld,' AS bin, COUNT(',fld,') AS ct
FROM ',tbl,'
GROUP BY bin
ORDER BY bin) x;');
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
/* Calls */
CREATE TEMPORARY TABLE IF NOT EXISTS results (
fld VARCHAR(30), bin VARCHAR(30), ct FLOAT);
CALL sproc('itemQty','someData');
CALL sproc('itemCat','someData');
SELECT * FROM results;
In the end, the temporary table results
has the output of 2 calls.