Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would the exact same SQL query result with a different execution plan when executed via the sp_executeSQL procedure?

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

like image 241
Nathan Tregillus Avatar asked Mar 30 '11 14:03

Nathan Tregillus


People also ask

Why does SQL plan change?

A plan change can occur due for a variety of reasons including but not limited to the following types of changes occurring in the system: optimizer version, optimizer statistics, optimizer parameters, schema/metadata definitions, system settings, as well as SQL profile creation.

What are the benefits of using Sp_executesql over EXEC?

sp_executesql allows for statements to be parameterized, Therefore It's more secure than EXEC in terms of SQL injection.

What is EXEC Sp_executesql in SQL?

The sp_executesql is a built-in stored procedure in SQL Server that enables to execute of the dynamically constructed SQL statements or batches. Executing the dynamically constructed SQL batches is a technique used to overcome different issues in SQL programming sometimes.

Why we use Sp_executesql in SQL Server?

sp_executesql can be used instead of stored procedures to execute a Transact-SQL statement many times when the change in parameter values to the statement is the only variation.


2 Answers

see this

basically, there can be multiple [execution] plans for the same procedure

like image 52
Beth Avatar answered Oct 05 '22 03:10

Beth


Consider this. When you execute a stored procedure, this procedure will have its own execution plan. When you execute a query statement, again it will have its own execution plan. Now when using sp_executeSQL you are running this stored procedure to execute a query dynamically. So in essence its execution plan is the combination of sp_executeSQL and your query.

like image 28
John Hartsock Avatar answered Oct 05 '22 02:10

John Hartsock