如何使用参数选择要使用的查询?

时间:2019-08-20 18:39:47

标签: sql-server ssms

我正在制作一个报告,并且我需要此报告上的显示帐户,这些帐户在过去两年中的销售额超过了5,000美元,或者在运行本报告时,迄今已完成了超过500美元。

DECLARE @Options INT = 1

--When I put 0 then
SELECT 
    Customer, SUM(Price) AS SALES
FROM 
    SOP30200 (NOLOCK)
WHERE 
(PostDate BETWEEN DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) AND getdate())
GROUP BY Customer
HAVING SUM(Price) > 500
ORDER BY Customer

--When I put 1 then
SELECT 
    Customer, SUM(Price) AS SALES
FROM 
    SOP30200 (NOLOCK)
WHERE 
    PostDate BETWEEN DATEADD(Year,-2,GETDATE()) AND (GETDATE())
GROUP BY Customer
HAVING SUM(Price) > 5000
ORDER BY Customer

3 个答案:

答案 0 :(得分:1)

用最简单的术语来说,像这样:

IF @Options = 1
  BEGIN
   ... query 1
  END
ELSE
  BEGIN
   ... query 2
  END
ELSE

答案 1 :(得分:1)

一种方法是使用CASE语句:

SELECT 
    Customer, SUM(Price) AS SALES
FROM 
    SOP30200 (NOLOCK)
WHERE 
    PostDate BETWEEN CASE @Options
            WHEN 0 THEN DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
            WHEN 1 THEN DATEADD(Year,-2,GETDATE())
            ELSE NULL
        END
        AND (GETDATE())
GROUP BY Customer
HAVING SUM(Price) > CASE @Options
        WHEN 0 THEN 5000
        WHEN 1 THEN 500
        ELSE NULL
    END
ORDER BY Customer;

这看起来并不漂亮,但是应该可以工作(我可能遗漏了语法错误)。

另一种方法是声明变量并在查询中使用它们:

DECLARE @PriceTreshold INT = CASE @Options
        WHEN 0 THEN 5000
        WHEN 1 THEN 500
        ELSE NULL
    END;
DECLARE @PostDateFrom DATETIME2 = CASE @Options
        WHEN 0 THEN DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
        WHEN 1 THEN DATEADD(Year,-2,GETDATE())
        ELSE NULL
    END;

SELECT 
    Customer, SUM(Price) AS SALES
FROM 
    SOP30200 (NOLOCK)
WHERE 
    PostDate BETWEEN @PostDateFrom AND (GETDATE())
GROUP BY Customer
HAVING SUM(Price) > @PriceTreshold
ORDER BY Customer;

您的查询并没有什么不同,只是基于@Options具有不同的过滤条件。

如果它们确实有很大不同,则可以使用这种语法:

IF @Options = 0
BEGIN
    -- SQL query If @Options = 0
END
ELSE IF @Options = 1
BEGIN
    -- SQL query If @Options = 1
END

但这不是您所需要的。

答案 2 :(得分:0)

一个简单的方法是在第一个查询的WHERE子句中添加“ AND @Options = 0”,在第二个查询的WHERE子句中添加“ AND @Options = 1”。然后通过在两个查询之间加入UNION将它们合并为一个查询。