SQL WHILE – SQL For Programmers
The IF statement we looked at on Tuesday was pretty tame compared to the WHILE construct.
Actually, the main thing you need to keep in mind is that WHILE is all you have. There is no such thing as a FOR loop or a DO WHILE loop. So, you have to force WHILE to do those for you.
The basic syntax of WHILE looks like this:
DECLARE @someString as VARCHAR WHILE @someString='ABC' BEGIN SELECT * FROM someTABLE SELECT * FROM someOtherTABLE END
So if you want a FOR/NEXT loop, you’ll need to write:
DECLARE @someInt as int SET @someInt = 0 WHILE @someInt < 20 BEGIN /* useful code here */ SET @someInt = @someInt + 1 END
and a DO WHILE loop would be something like:
DECLARE @someInt as int SET @someInt = 0 WHILE @someInt = 0 BEGIN /* useful code here */ IF *some exit condition */ SET @someInt = 1 END
Once you learn to substitute those constructs for your normal FOR/NET or DO WHILE code, it becomes rather easy to deal with.
Now if they’d just replace BEGIN with { and END with } I think I could live with this.
Other post in SQL For Programmers
- SQL For Developers - 9 Reasons to bother - August 13th, 2008
- MSSQL CREATE and DROP Database - SQL for Programmers - August 20th, 2008
- MSSQL CREATE TABLE - SQL For Programmers - August 22nd, 2008
- SQL For Programmers - ALTERing the TABLE - September 1st, 2008
- SQL For Programmers - Finding a String - September 3rd, 2008
- SQL For Programmers - Finding IN a List - September 8th, 2008
- SQL For Programmers - Stored Procedure Basics - September 16th, 2008
- Basic SQL Commands - SQL For Programmers - September 18th, 2008
- SQL IF/WHILE Blocks - SQL For Programmers - September 30th, 2008
- SQL WHILE - SQL For Programmers - October 2nd, 2008
- Temporary Tables - SQL For Programmers - October 7th, 2008
- SQL CURSOR - SQL For Programmers - October 13th, 2008
- SQL CURSOR Performance - SQL For Programmers - October 22nd, 2008
- Random in SQL - SQL For Programmers - November 4th, 2008
- SQL - Filtering WHERE condition on two rows - November 26th, 2008
- SQL - Transactions - April 15th, 2009
- SQL For Programmers – New Question - July 6th, 2009
- SQL SELECT CASE Instead of IIF - October 20th, 2009
- SQL For Programmers - Stored Procedures (Better than LINQ) - August 28th, 2012
Related Post
2 Pingbacks/Trackbacks
- 02 October 2008 at 7:10am
- Dew Drop - October 2, 2008 | Alvin Ashcraft's Morning Dew 05 October 2008 at 4:10pm
- Weekly Link Post 62 « Rhonda Tipton’s WebLog
[...] SQL WHILE - SQL For Programmers (Dave M. Bush) ...
[...] across a great article titled SQL WHILE - SQL For Programmers. It demonstrates how ...




Pingback: Dew Drop - October 2, 2008 | Alvin Ashcraft's Morning Dew
Pingback: Weekly Link Post 62 « Rhonda Tipton’s WebLog