I have a stored procedure in a MS-SQL 2005 database that:
The SP takes two parameters, which are then used in the first query.
When I run the SP for a given set of parameters, it takes 3 minutes to execute.
When I execute the contents of the SP as a regular T-SQL batch (declaring and setting the parameters beforehand), it takes 10 seconds. These numbers are consistent across multiple sequential runs.
This is a huge difference and there's no obvious functional changes. What could be causing this?
Reindexing my tables (DBCC REINDEX) sped up the SP version dramatically. The SP version now takes 1 second, while the raw SQL takes 6.
That's great as a solution to the immediate problem, but I'd still like to know the "why".
It might have been exactly due to the fact that in SP the execution plan was cached and it was not optimal for the data set. When data set depends greatly on the parameters or changes considerably between invocations it's better to specify 'with recompile' in 'create proc'. You lose a fraction of a second on recompilation, but may win minutes on execution.
PS Why cannot I comment? Only "Your Answer" is available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With