使用动态选择mysql存储过程的列

时间:2013-06-25 10:29:01

标签: mysql stored-procedures query-parameters

我正在尝试编写一个存储过程来从数据库中提取一些聚合统计信息。

我想修改程序以允许动态选择列。

我的第一个想法是使用Case或IF语句来选择不同的列

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//

现在我不认为案例陈述是为了这个目的,目前它不起作用......是否有可能实现上述目标?

仅供参考 - 我完全清楚我可以选择两列,但我不希望将这两列都暴露给我的网络应用。

1 个答案:

答案 0 :(得分:0)

更改此

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

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

最后它应该是这样的:

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//

我修复了一些语法错误。