I have a multiple selection listbox on a web form which lists various internal activity codes, and users can filter the results of a query based on the codes selected. I can easily add a single code as a parameter to my stored procedure and filter the results with a WHERE clause like so:
WHERE ActivityCode = @ActivityCode OR @ActivityCode is null
but what is the best practise for handling multiple codes, especially when the number of codes selected is arbitrary?
This:
…works, but is not sargable.
If you only have one optional parameter, you can use an IF:
FYI: SQL doesn’t support a variable to represent a comma separated list – you have to use dynamic SQL for that.
SQL Server 2005+