I’ve read that using Dynamic SQL in a stored procedure can hurt performance of your stored procedures. I guess the theory is that the store procedure won’t store an execution plan for SQL executed via EXEC or sp_executesql.
I want to know if this is true. If it is true, do I have the same problem with multiple nested IF blocks, each one with a different “version” of my SQL statement?
If you have multiple nested IF blocks then SQL Server will be able to store execution plans.
I’m assuming that the IFs are straightforward, eg. IF @Parameter1 IS NOT NULL
SchmitzIT’s answer is correct that SQL Server can also store execution paths for Dynamic SQL. However this is only true if the sql is properly built and executed.
By properly built, I mean explicitly declaring the parameters and passing them to sp_executesql. For example
As you can see the sqlcommand text does not hardcode the paramer values to use. They are passed separately in the exec sp_executesql
If you write bad old dynamic sqL
then SQL Server won’t be able to store execution plans