Best Practice in Looping through the rows in a table

Hi there,

What is the best practice when it comes to iterating thru each row in a table?  Do I have to use CURSORS to achieve this or is there a better/more efficient way to do this?

I understand that using CURSORS is not a good programming practice.

For example, if I have a table that contains 500 rows or even maybe 5 million rows and i want to loop thru each row and then based on some logic as to perform some task.

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SQL is a set-based language. Efficient SQL works with sets. Loops are a procedural construct, not a set-based construct. That's why loops are an inefficient way to work in a database. A cursor will allow you to loop over all rows. However, I think the key is in this part of your statement:
"based on some logic as to perform some task".

Chances are pretty good that "some logic" can be used to define subsets of the rows in the table. Then if you implement a procedure or run a series of statements that define the logic to select the subset on which you want to perform each different member of "some task". It will run more efficiently.

Does that help?


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
singhchAuthor Commented:
Well not really.  anyway your explanation is fine.

maybe i will post another question on a specific task that i want to achieve. And maybe you can advise how you would go about implementing the solution.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.