As the title states, I don't understand why the sp_executeSQL would generate a completely different execution plan than running the query from Sql Management Studio.
My query in question will take 3 seconds when run from SQL management Studio, where as the query run in management studio via sp_executeSQL will take 5 minutes.
I've updated statistics, and reviewed indexes, but the fact remained in my head that the execution plan from sp_executeSQL was FAR worse than running the sql directly from my management studio.
So here is my question: Why would the execution plans differ SO much between running the query in these two different ways?
Thanks
sp_executesql
the plan is compiled according to the value of the first set of parameters it sees. When your query has constants and the plan is not auto parameterised then SQL Server can sometimes use contradiction detection to not execute part of the plan and also will use cardinality estimates for those specific values. – Carmarthenshire