So basically I have this relatively long stored procedure. The basic execution flow is that it SELECTS INTO
some data into temp tables declared with he #
This is because of parameter snipping. But how can you confirm it?
Whenever we supposed to optimize SP we look for execution plan. But in your case, you will see an optimized plan from SSMS because it's taking more time only when it called through Code.
For every SP and Function, the SQL server generates two estimated plans because of ARITHABORT option. One for SSMS and second is for the external entities(ADO Net).
ARITHABORT is by default OFF in SSMS. So if you want to check what exact query plan your SP is using when it calls from Code.
Just enable the option in SSMS and execute your SP you will see that SP will also take 12-13 minutes from SSMS. SET ARITHABORT ON EXEC YourSpName SET ARITHABORT OFF
To solve this problem you just need to update the estimate query plan.
There are a couple of ways to update the estimate query plan. 1. Update table statistics. 2. recompile SP 3. SET ARITHABORT OFF in SP so it will always use query plan created for SSMS (this option is not recommended) For more options please refer to this awesome article - http://www.sommarskog.se/query-plan-mysteries.html