简体   繁体   中英

Slow running stored procedure in SQL Server 2008 R2

So it's rare that I get completely confused but wanted to see what others thought about what I'm experiencing.

I've been asked to look at a slow running stored procedure. Currently takes around 8-12 minutes to run.

So I noticed a useful index was missing and added it - now takes 8 seconds. But if I restart SQL Server and re-run the stored proc it's taking 8-12 minutes again.

If I then stop the query and delete the new index then re-run the stored proc it takes seconds again. Bizarre.

Has anyone ever experienced anything like this? The stored procedure is calling a View if that makes any difference.

Q. if I restart SQL Server and re-run the stored proc it's taking 8-12 minutes again.

When you perform your query, the data is read into memory in blocks. These blocks remain in memory but they get "aged". This means the blocks are tagged with the last access and when Sql Server requires another block for a new query and the memory cache is full, the least recently used block (the oldest) is kicked out of memory. (In most cases - full tables scan blocks are instantly aged to prevent full table scans overrunning memory and choking the server).

Q. If I then stop the query and delete the new index then re-run the stored proc it takes seconds again.

What is happening here is that the data blocks in memory from the first query haven't been kicked out of memory yet so can be used for your second query, meaning disk access is avoided and performance is improved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM