Using Dynamically selecting columns of mysql stored procedure

*爱你&永不变心* 提交于 2019-12-25 14:00:35

问题


I am trying to write a stored procedure to pull off some aggregate statistics from a database.

I would like to amend the procedure to allow dynamic selection of columns.

My first thoughts were to use a Case or IF statement to select different columns

DELIMITER//
CREATE PROCEDURE 'procStats'(IN buySell varchar(4))
SELECT 

    CASE 
        WHEN buySell = 'Buy' THEN AVG(salesTransactions.BuyPrice) AS AveragePrice,
        WHEN buySell = 'Sell' THEN AVG(salesTransactions.SellPrice) AS AveragePrice,
    END CASE;

    MONTHNAME(salesTransactions.DateOfTransaction) as TransactionMonth
FROM
    salesTransactions
GROUP BY 
    TransactionMonth
LIMIT 6;
END//

Now I don't think that case statements are intended for this purpose, and it currently doesn't work... Is it possible to achieve the above??

FYI - I am fully aware that i could just select both columns however I do not wish to expose both columns to my web app.


回答1:


Change this

CASE 
    WHEN buySell = 'Buy' THEN AVG(salesTransactions.BuyPrice) AS AveragePrice,
    WHEN buySell = 'Sell' THEN AVG(salesTransactions.SellPrice) AS AveragePrice,
END CASE;

to

CASE buySell
    WHEN 'Buy' THEN AVG(salesTransactions.BuyPrice) 
    WHEN 'Sell' THEN AVG(salesTransactions.SellPrice)
END AS AveragePrice,

In the end it should look like this:

DELIMITER//
CREATE PROCEDURE procStats (IN buySell varchar(4))
BEGIN
SELECT 

    CASE buySell
        WHEN 'Buy' THEN AVG(salesTransactions.BuyPrice) 
        WHEN 'Sell' THEN AVG(salesTransactions.SellPrice)
    END AS AveragePrice,

    MONTHNAME(salesTransactions.DateOfTransaction) as TransactionMonth
FROM
    salesTransactions
GROUP BY 
    TransactionMonth
LIMIT 6;
END//

I fixed some more syntax errors.



来源:https://stackoverflow.com/questions/17294943/using-dynamically-selecting-columns-of-mysql-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!