I have a complex SQL Query, that needs to be filtered further. Part of the WHERE clause looks like this:
Where P.PeriodID in (36, 37)
I need to get it to look more like this:
Where P.PeriodID in dbo.GetPeriodsInRange(@startDate, @endDate)
The function must return a list of PeriodIDs to be used by the IN statement. I really suck at writing functions, so I need some assistance. Also, I’m not sure how to deal with edge cases, say if there are no periods in the specified date range.
The function above doesn’t need to get evaluated for each row. It will be the same for each row, so there is probably some optimisation that can be done, maybe before the query is executed.
I’m pretty sure I’m breaking several “best practices” here, so please point them out to me if there is a better way to do this. However, performance is not an issue, so I’m willing to sacrifice performance in favour of simplicity.
My question applies to T-SQL (MS SQL Server 2000/2005)
My solution would be to create a function as Mudu suggested. I m using this.
From the link:
After that i use a inner join like this:
You could generate a String and then execute it but it is not very advised here, I think.