Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would a Stored Procedure run slower than naked T-SQL?

I have a stored procedure in a MS-SQL 2005 database that:

  • Creates two temp tables
  • Executes a query with 7 joins but is not otherwise terribly complex
  • Inserts the results into one of the temp tables
  • Executes two more queries (no joins to "real" tables) that puts records from one of the temp tables into the other.
  • Returns a result set from the second temp table
  • Drops both temp tables

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?

UPDATE

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".

like image 923
Craig Walker Avatar asked Dec 13 '22 20:12

Craig Walker


1 Answers

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.

like image 96
vaso Avatar answered Jan 29 '23 13:01

vaso