Skip to content
Advertisement

What is the most efficient way to optimize a filter based on parameters on a SQL Server stored procedure?

Right now I have something like:

… and so on, so in the end I’ll have

I think this is going to work, but it doesn’t seems efficient to me. Is there a way to optimize this process and filter information with multiple parameters, with the option of some of them being null?

Advertisement

Answer

The most efficient method to do this type of kitchen-sink query is actually the way you are doing it now, except that you should properly parameterize each filter.

This is because a single plan will be cached for every possible combination of filters. This means that whenever that combination of filters is used again, even with different values, a cached plan will be used.

Whereas if you use OPTION(RECOMPILE), a new plan is generated on every run. And OPTION(OPTIMIZE FOR UNKNOWN) will usually just get you an overall not-that-great plan.

So you parameterize it with sp_executesql, like this

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement