Reputation: 13828
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
Upvotes: 1
Views: 748
Reputation: 81680
why this simple sql statement takes so much CPU
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.
Upvotes: 2
Reputation: 115600
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
Upvotes: 0
Reputation: 2804
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:
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
Upvotes: 3