Skip to content
Advertisement

Does declaring variables inside an exec improve SQL query plans?

I have a bunch of stored procedures that I’m looking to optimize and want to know if changing from having the variables injected into the WHERE condition to having them inject into a variable declaration will help

The current statements look like this where the ids are passed into the stored procedure and then injected into the EXEC

Would there be any benefit of changing to something like this where the injected values are done into a variable?

Advertisement

Answer

Doing it the first way

means that the a new query plan could be generated for every run. While it is true that auto-parameterization may work here, it may not, and therefore you are undergoing the cost of recompilation every time.

Meanwhile the second version,

doesn’t really help things, as the whole batch is changing each time, so you still get a recompilation. It will also force auto-parameterization off, and the fact you are using local variables means parameter sniffing is disabled also.

As mentioned by @DanGuzman, you could use sp_executesql

This will get you a cached plan, with parameter sniffing.

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