在where语句中使用Case和用户输入

时间:2013-07-05 15:31:52

标签: sql-server-2008

我正在尝试添加所有可能的年度费用,但我的案例陈述没有异味。

如果我选择2013年,我希望能够将所有费用从2006年添加到2013年。如果没有Case声明,有没有更好的方法呢?或者我是走错路。

 SELECT ID, Sum(Amount) As Total
FROM ABCD
WHERE Expenses = 'Actual' AND  
      AcountType = 'Expense' AND 
      CASE WHEN 'Myselectionparameter' = 2013 
           THEN ( YearID =2013 or YearID = 2012 or YearID = 2011 or YearID = 2010 or YearID = 2009 or YearID = 2008  Or YearID = 2007 or YearID = 2006 )
      END 
GROUP BY ID

2 个答案:

答案 0 :(得分:1)

所以Myselectionparameterint参数?

SELECT ID, Sum(Amount) As Total
FROM   abcd 
WHERE  ... 
       AND ( @Myselectionparameter IS NULL 
              OR YearID BETWEEN 2006 AND @Myselectionparameter ) 
GROUP  BY id 

答案 1 :(得分:1)

让我们假设你的问题是关于一个参数,在这种情况下,你在param名称之前使用@。

那么你有一个特别的答案......

SELECT ID, Sum(Amount) As Total
FROM ABCD
WHERE Expenses = 'Actual' AND  
      AcountType = 'Expense' AND 
      (@Myselectionparameter = 2013 AND YearID  BETWEEN 2006 AND 2013)
      END 
GROUP BY ID

如果参议院说2011年怎么样?你想从2006年到2011年吗?在这种情况下,你有一般答案:

SELECT ID, Sum(Amount) As Total
FROM ABCD
WHERE Expenses = 'Actual' AND  
      AcountType = 'Expense' AND 
      YearID  BETWEEN 2006 AND @Myselectionparameter
GROUP BY ID