如果Else在where子句中

时间:2013-01-29 20:40:16

标签: sql-server-2008 tsql stored-procedures

以下是我所拥有的片段:

select something from myTable
where curentFlag = 'Y'
and
case when @Year2 is not NULL then  
 AYEAR >= @Year AND AYEAR <= @Year2
else
 AYEAR= isnull(@Year ,AYEAR)  
end
        ADATE = ISNULL(@Date, ADATE) 

但这会产生:

  

'&gt;'附近的语法不正确。
  “ADATE”附近的语法不正确。

用户应该能够搜索一年(等于)或一年的范围。所以我要么只是传递@YEAR,要么传递@YEAR@YEAR2。那么让我们说我的数据集:

DECLARE @y TABLE(AYEAR INT);
INSERT @y VALUES(2008),(2010),(2010);

现在我有了这些变量:

DECLARE @YEAR INT, @YEAR2 INT;
  • 如果我传入@YEAR = 2008我应该得到1个结果。
  • 如果我传入@YEAR = 2010我应该得到2个结果。
  • 如果我传入@YEAR = 2008@YEAR2 = 2010,我应该获得全部3个结果。

2 个答案:

答案 0 :(得分:3)

CASE是一个返回单个值的表达式。它不能用于控制流逻辑。

如果您确定将始终填充@Year并且有时只会填充@Year2,那么这个更简单的逻辑应该有效:

WHERE CURRENTFLAG = 'Y'
AND AYEAR BETWEEN @Year AND COALESCE(@Year2, @Year)
AND ADATE = COALESCE(@Date, ADATE);

您可以通过一个非常简单的示例来尝试:

DECLARE @y TABLE(AYEAR INT);
INSERT @y VALUES(2008),(2010),(2010);

DECLARE @YEAR INT = 2008, @YEAR2 INT = 2010;
--DECLARE @YEAR INT = 2008, @YEAR2 INT = NULL;
--DECLARE @YEAR INT = 2010, @YEAR2 INT = NULL;

SELECT AYEAR FROM @y 
  WHERE AYEAR BETWEEN @YEAR AND COALESCE(@YEAR2, @YEAR);

答案 1 :(得分:0)

 where CURRENTFLAG = 'Y' 
    case when @Year2 is not NULL then  --after THEN should be statement or BEGIN block not AND
 and AYEAR >= @Year AND AYEAR <= @Year2
    else
     AND  AYEAR= isnull(@Year ,AYEAR)   -- here also
    end
        and    ADATE = ISNULL(@Date, ADATE)