如何在不使用CASE的情况下有条件地添加WHERE子句

时间:2016-10-02 21:21:36

标签: sql sql-server conditional where

我想在存储过程的WHERE部分有条件地添加一个子句,但我知道使用CASE非常糟糕。这基本上就是我要做的事情:

@StartDate
@EndDate
@ClientID
SELECT field_1, field_2, datefield_3 
from tblTable
Where datefield_3 Between @StartDate AND @EndDate
 --If @ClientID > 0 then add
AND field_1 = @ClientID

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

这是:

...
Where datefield_3 Between @StartDate AND @EndDate
AND (field_1 > 0 OR field_1 = @ClientID)

答案 1 :(得分:0)

@StartDate
@EndDate
@ClientID


IF ClientID>0
BEGIN
SELECT field_1, field_2, datefield_3 
from tblTable
Where datefield_3 Between @StartDate AND @EndDate
AND field_1 = @ClientID
END
ELSE
BEGIN
  SELECT field_1, field_2, datefield_3 
from tblTable
Where datefield_3 Between @StartDate AND @EndDate
END 

答案 2 :(得分:0)

一样简单:

@StartDate
@EndDate
@ClientID
SELECT field_1, field_2, datefield_3 
from tblTable
Where datefield_3 Between @StartDate AND @EndDate
  AND (@ClientID <= 0 OR field_1 = @ClientID)

如果@ClientID&lt; = 0,则不评估附加条件。即if @ClientID&gt; 0,field_1 = @ClientID被评估!