在where子句的中间使用if基于if条件

时间:2012-07-24 08:52:48

标签: sql sql-server-2008 tsql

Select * from MyTable 
    where myField = 1
    And myImportantField ???
    ...

我有以下参数:

@DoCalculateValues bit,  
@FromValue int,  
@ToValue int  

我需要这个

if @DoCalculateValues = 1 then  
check if myImportantField is between @FromValue and @ToValue  
else  
ignore values, something like "And myImportantValue = myImportantValue"
请注意,这一切都发生在“... WHERE ...... AND ...”条款中间

2 个答案:

答案 0 :(得分:3)

Select * from MyTable 
where myField = 1
And (@DoCalculateValues = 0
or myImportantField between @FromValue and @ToValue)

答案 1 :(得分:0)

Select * from MyTable  
where myField = 1 
And ((myImportantField between @FromValue and @ToValue and @DoCalculateValues = 1)
OR  ( @DoCalculateValues <> 1))