old question but want to add that i just found using
where
CASE WHEN @id = 0
THEN 1
ELSE id
END
=
CASE WHEN @id = 0
THEN 1
ELSE @id
END
this is from these steps:
where id = @id
check if @id is null (or invalid) or have valid value so replace @id using case:
where id =
CASE WHEN @id is null
THEN 0
ELSE @id
END
this is will end up as
where id = 0 -- if @id is null, still affected your query
where id = @id -- if @id have valid value
because we want use this "where" clause only if have valid data then we change id too
where
CASE WHEN @id is null
THEN 0
ELSE id
END
=
CASE WHEN @id is null
THEN 0
ELSE @id
END
then will end up as
where 0 = 0 -- if @id is null and it doesn't affect your query
where id = @id -- if @id have valid value
don't forget if id is varchar, use 0 as '0'
CASE WHEN @id is null
THEN '0'
ELSE id
END
i use this in my project and working well, even i use more than 1 of this in one query. please let me know if this query costing time at larger data