Currently I have to work a bit more with SQL Server and I’ve read about cursors and how you should try to avoid them, because they’re using a lot of resources and because they’re slow.
Now I’ve tried to do some basic stuff with the cursor and tried to rebuild it with a while loop. At the end the cursor was ~10x faster than the while loop, while resources were about 60% to 40%.
Maybe because I have a strange example exercise?
This is about the exercise I gave myself:
- Iterate through a table, this table has exactly one column: “Names”, containing about 1000 names.
- Print each name separately.
It’s pretty easy with the cursor, but for the while-loop I need a counter or something. As the table has no index, I can’t use that. So my solution was, that I created a temporary table, added all names to the table and include an index (or a row number). But the insert-operation takes about 95% of the time and at the end the while-loop is slower than the cursor.
Edit:
Another thing I tried was to use a WITH Names_Rows AS... and added Row_Number() as column and then used the while loop to iterate through the Names_Rows construct. But that took even longer.
Did I miss an easy way to iterate through a table using while without having an index?
The reason for avoiding cursors is because you are performing imperative one row at a time operations rather than declarative set based operations.
Replacing a cursor with a while loop will not in itself magically make the performance better and may well make performance worse as you have found out. The difference in performance between the two will depend upon your exact code / table structures and the cursor options you choose as covered in this series of articles.
To print out all names from the table in a more set based manner you could do