简体   繁体   中英

SQLSERVER 2008 executing a select statement repeatedly causes High CPU usage

Is there any alternative from using a loop in my code to execute a select statement repeatedly to get value of live status column in my table?

It's a simple "Select status from dbo.mytable". But,I have no idea why this simple sql statement takes so much CPU when being executed on a loop.

Right now,the loop makes sqlserver use more than 50% of the CPU. Please advice any alternative or a way to solve this.

Thanks.

Edit: Before someone says "why do you need a loop?", "don't use a loop",etc, let me explain that this is not my requirement. It's from my company.Thanks

As stated we need some code to properly debug but these are my thoughts...

How fast is this loop going? If it is quite literally

while (x == false) {
x = SQL STATEMENT
}

then yes, you will cause a massive amount of SQL load because the query will be running many thousands of times a second.

If on the other hand you are using a timer and looping every few seconds then such load is unusual unless:

  • There are a large number of clients using the application so in effect there are multiple loops all hitting the server at the same time
  • You are selecting a very large amount of data
  • Your indexes aren't especially efficient
  • You're not breaking out of previously completed loops causing unnecessary load

Finally you could perhaps look at building some caching into your DAL to reduce the number of queries actually making it to the SQL server. You can implement your own logic to do this or perhaps use something like this: http://bltoolkit.net/Doc.CacheAspect.ashx

why this simple sql statement takes so much CPU

  • Because it already is a loop (SELECT with no WHERE condition returns all the rows) and need not be called on a loop
  • Perhaps because you have too many rows
  • Maybe because no indexes on status

Having a non-clustered index on status can hugely improve the performance. Reason is SQL Server would not need to touch the table at all. But still does not make much sense to call it in a loop.

How often does your loop call the statement?

There is a huge difference between

Foreach day 
  at noon: call query

and

Foreach millisecond
  call query

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