Asp*_*bie 14 sql-server stored-procedures if-statement where-clause
我需要在sql中的where子句中使用if语句.
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
Run Code Online (Sandbox Code Playgroud)
注意:这不是完整的代码.所有内容都在SP中定义.我只需编写理解该问题所需的代码.
提前致谢.
SELECT *
FROM Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND (isnull(@Value,1) <> 2
OR I.RecurringCharge = @Total
OR @Total is NULL )
AND (isnull(@Value,2) <> 3
OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
OR @Total is NULL )
Run Code Online (Sandbox Code Playgroud)
基本上,你的病情是
if (@Value=2)
TEST FOR => (I.RecurringCharge=@Total or @Total is NULL )
Run Code Online (Sandbox Code Playgroud)
翻了个身,
AND (isnull(@Value,1) <> 2 -- A
OR I.RecurringCharge = @Total -- B
OR @Total is NULL ) -- C
Run Code Online (Sandbox Code Playgroud)
当(A)为真时,即@Value 不是 2,无论B和C结果如何,[A或B或C]都将变为TRUE.B和C实际上只在检查时才会检查@Value = 2,这是初衷.
您必须使用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
Run Code Online (Sandbox Code Playgroud)