需要MySQL解决方法将变量\参数传递到视图中吗?

时间:2013-01-24 22:12:28

标签: mysql view sql-view

我想将一个变量\参数传递给视图以按日期范围过滤。由于我在视图中进行分组,因此我无法将where子句放在视图外部。

我已经阅读了很多关于此的帖子,但还未能让它正常运行。我已经看到将参数传递给视图的大多数解决方法都涉及使用函数来返回值,这就是我遇到的问题。

/* My current view that I want to pass in start and end dates */
CREATE VIEW Total_Sales_By_Product_Num AS
SELECT products_all_fields.*,
    Sum(<a bunch of code removed for this sample>) AS Item_Qty_Requested_Total, 
    Sum(<a bunch of code removed for this sample>) AS Item_Qty_Accepted_Total,  
    Sum(<a bunch of code removed for this sample>) AS Total_Sales_Dollars
FROM products_all_fields
    LEFT OUTER JOIN (web_orders_items
        INNER JOIN web_orders_header
            ON  web_orders_items.Web_Order_Num = web_orders_header.Web_Order_Num )
        ON  products_all_fields.Product_Num = web_orders_items.Product_Num
WHERE web_orders_header.Order_Date BETWEEN fn_GetStartDate() AND fn_GetEndDate()
GROUP BY products_all_fields.Product_Num
ORDER BY products_all_fields.Description

将参数返回到视图的函数:

CREATE FUNCTION fn_GetStartDate ()
    RETURNS DATE
    DETERMINISTIC NO SQL
BEGIN
    RETURN @StartDate;
END

CREATE FUNCTION fn_GetEndDate ()
    RETURNS DATE
    DETERMINISTIC NO SQL
BEGIN
    RETURN @EndDate;
END

这不起作用,它不返回任何数据,我知道我正在做一些愚蠢的事情

set @fn_StartDate := '2012-01-01';
set @fn_EndDate := '2012-02-01';
select * from Total_Sales_By_Product_Num

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

唉唉!!!我得到了它的工作,我觉得自己像个白痴,但我的双引号并没有在我的日期任务中单引号。它似乎现在工作。我将把这篇文章留给未来的人们来搜索如何做到这一点。

答案 1 :(得分:0)

你需要

SET @fn_StartDate = fn_GetStartDate('2012-01-01')

与@fn_EndDate相同

然后在你的视图中

WHERE web_orders_header.Order_Date BETWEEN @fn_StartDate.....

然而,这只是如何调用函数的语法。你还在尝试将参数传递给视图,据我所知,这是不可能的。尝试将所有View逻辑放入函数中。

答案 2 :(得分:0)

它应该按以下方式工作:

set @StartDate := '2012-01-01';
set @EndDate := '2012-02-01';
select * from Total_Sales_By_Product_Num;