Looping Structures

Many times within an application, you will need to loop. Looping is the process of repeating a certain section of code until a specific criteria is met. SQL Server can loop. There are only two real looping structures within SQL Server and they are extremely similar. One is a loop using a WHILE statement and the other is a loop that utilizes a GOTO statement. Of course, as anyone who has ever taken a programming class can tell you WHILE is the preferred method; you should try to avoid using GOTO because it can create code that's extremely difficult to read.

WHILE Loop

The WHILE loop is a loop in which you check the criteria before the statement executes. All you have to do is specify the WHILE keyword, the criteria you ...

Get Writing Stored Procedures for Microsoft SQL Server now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.