在where子句中选择两列之间的情况,SQL Server

时间:2015-07-12 14:09:05

标签: sql-server tsql

我在where子句中有两列可供选择,两列都是日期列。 Date1和Date2。

我满足这些条件。

When @temp1= 1 and @temp2= 0 then Date1 between (@startdate and @enddate)
When @temp1= 0 and @temp2= 1 then between (@startdate and @endDate)
when @temp1= 1 and @temp2 =1 then Date1 between (@startDate and @endDate) and Date2 between (@startdate and @endDate)    

我必须写这样的东西

Case when @temp1 = 1 then Date1 between  (@startdate and @enddate) 
     when @temp2 = 1 then Date2 between  (@startdate and @enddate) 
     when @temp1 = 1 and @temp2 = 1 then (Date1 between  (@startdate and @enddate) and  Date2 between  (@startdate and @enddate)

请提前帮助,请提供帮助

1 个答案:

答案 0 :(得分:3)

您可以使用CASE这样的句子,而不是WHERE

WHERE
    (@temp1 = 0 OR Date1 between (@startdate and @enddate)) AND
    (@temp2 = 0 OR Date2 between (@startdate and @enddate))

如果@temp1 = 0,则满足第一个条件的第一部分,并且不评估条件Date1 between (@startdate and @enddate)。但是,如果@temp1 = 1,则会评估between@temp2Date2条件

也是如此