如何在SQL的Where子句中使用If语句? [英] How to use If Statement in Where Clause in SQL?
本文介绍了如何在SQL的Where子句中使用If语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在sql中的where子句中使用if语句。
I need to use if statement inside where clause in sql.
Select * from Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND
(C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND
if (@Value=2)
begin
(I.RecurringCharge=@Total or @Total is NULL )
end
else if(@Value=3)
begin
(I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%' or @Total is NULL )
end
注意:这不是完整的代码。所有内容都在SP中定义。我只需编写理解该问题所需的代码。
Note:This is not the complete code.Everything is defined in SP.I Just written the code that was needed to understand the issue.
提前致谢。
推荐答案
你必须使用 CASE Statement / Expression
Select * from Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND
(C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND
CASE @Value
WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL)
WHEN 3 THEN (CASE WHEN I.RecurringCharge like
'%'+cast(@Total as varchar(50))+'%'
or @Total is NULL )
END
这篇关于如何在SQL的Where子句中使用If语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文