How to use Table output from stored MYSQL Procedure

后端 未结 3 757
陌清茗
陌清茗 2020-12-06 01:02

I\'ve been looking for the last hour or so and haven\'t found a conclusive answer to this seemingly simple problem:

How do you call a stored MYSQL function/p

3条回答
  •  广开言路
    2020-12-06 01:29

    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.

提交回复
热议问题