How to use Table output from stored MYSQL Procedure

后端 未结 3 755
陌清茗
陌清茗 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:21

    Here's a concrete example in MySql 8, based on @Michael-sqlbot's suggestion:

    -- Create some test data
    drop table if exists someData ;
    create table someData (itemId int, itemName varcharacter(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)
    ;
    
    -- Just checking that it's all there!
    select * from someData ;
    
    -- Define the proc
    delimiter //
    drop procedure if exists prcSomeData //
    create procedure prcSomeData()
        comment 'Create a temporary table called "tmpSomeData"'
    begin
        drop table if exists tmpSomeData ;
        create temporary table tmpSomeData as
            select itemCat
                , sum(itemQty) as 'itemsTot'
                , min(itemQty) as 'lowestQty'
                , max(itemQty) as 'highestQty'
                from someData
                group by itemCat
                order by itemCat
            ;
    end //
    delimiter ;
    
    -- Gotta run the proc to instantiate the temp table
    call prcSomeData() ;        -- produces a temporary table "tmpSomeData", exists for the session
    -- Now it's usable
    select * from tmpSomedata ;
    
    

    Which produces:

    itemCat|itemsTot|lowestQty|highestQty|
    -------|--------|---------|----------|
          1|      10|        1|         9|
          2|       1|        0|         1|
          3|      66|        7|        50|
          5|      12|       12|        12|
    

提交回复
热议问题