I have an varchar input variable that contains a comma delimited list of integers that are in one of the columns in my select statement. I know how to split the list and use this in a where clause for example:
DECLARE @ListOfAges Varchar
SET @ListOfAges = '15,20,25'
select p.Name, a.Age
from People p
left join Ages a on p.AgeKey = a.AgeKey
Where a.Age in (dbo.Split(@ListOfAges))
What I'd like to do is if the @ListOfAges var is null, to select everything, so something like this:
select p.Name, a.Age
from People p
left join Ages a on p.AgeKey = a.AgeKey
Where (@ListOfAges = null OR a.Age in (dbo.Split(@ListOfAges)))
Is this there a way to do this that performs better? Possibly without using the IN clause or not in the WHERE clause? I wasn't sure if including this in the join would be possible, or if an entirely different approach is recommended (such as not using comma separated input variables).
Thanks!
in (dbo.Split(@ListOfAges))within (15,20,25)? Is it substantially better? This is the upper bound for the performance that you can achieve by eliminating the split and doing nothing else. If this performance is not acceptable, you may want to see if there's other stuff to optimize there.