在Where子句中使用if语句

时间:2010-12-15 17:47:53

标签: sql-server-2005 tsql

是否可以在where子句中使用if staement?

WHERE (underwritername = 'underwriter') and (case when inceptiondate is null then (requestdate >= convert(datetime,'01/10/2009',103)) else (Inceptiondate >= convert(datetime,'01/10/2009',103)) ) and (requestdate <= convert(datetime,'31/10/2010',103))

基本上如果一列为null,我需要使用替代列进行选择。

非常感谢,

亚当

1 个答案:

答案 0 :(得分:6)

您可以使用CASE语句稍微改变一下:

WHERE (underwritername = 'underwriter') 
and (case when inceptiondate is null 
     AND requestdate >= convert(datetime,'01/10/2009',103) THEN 1 
     WHEN inceptiondate IS NOT NULL 
     AND Inceptiondate >= convert(datetime,'01/10/2009',103) THEN 1 ELSE 0 END = 1) 
and (requestdate <= convert(datetime,'31/10/2010',103))