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