question

clarke avatar image
clarke asked

TSQL - Loop

Hi Everyone: I am new to Tsql world and i am trying to learn Looping. Is there any good sites or Books to help me. Thanks for all your help.
sql-server-2005sqlsql-server
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
TimothyAWiseman avatar image
TimothyAWiseman answered
The main loop in T-SQL is a while loop. You can of course look it up in Books Online, but if you do much reading at all on SQL you will come across it repeatedly so I would just research T-SQL scripting in general and you will learn about the while loop. However, one of the things that many people learn later rather than sooner is that you should use loops sparingly. Most things in T-SQL should be done in a set based fashion where a loop tends to imply you are handling entities one by one. There are a few situations where you have to loop, but those tend to be more advanced cases. You might need a loop if you are iterating over tables for instance, or in certain types of string manipulation (I used it as a way to print blocks longer than 8000 characters as detailed here: [LongPrint][1] ) But as a general rule, in SQL Server if something can be done both with and without a loop, the solution that does not use the loop will tend to be faster and shorter. **Edit to respond to question:** There are many articles about that out there, but I would start with [The Road to Professional Database Development: Set-Based Thinking][2] and then take a look at some of [Jeff Moden's][3] articles, most of them deal with set based work. Also, its a book rather than an article but you might like SQL for Smarties. [1]: http://www.sqlservercentral.com/scripts/Print/63240/ [2]: http://www.simple-talk.com/sql/database-administration/the-road-to-professional-database-development-set-based-thinking/ [3]: http://www.sqlservercentral.com/Authors/Articles/Jeff_Moden/80567/
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

clarke avatar image clarke commented ·
Thanks for the suggestion. Possible to provide more info regarding set based fashion ?
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.