The WHILE Loop

Learn how to use the WHILE loop in T-SQL.

The WHILE loop is one of the most straightforward constructs in T-SQL. It is easy and intuitive to use because it works the same as in other programming languages.

Syntax

The WHILE loop executes a block of code while the condition holds. The syntax for this is:

WHILE [Condition]
BEGIN
    [Code to execute]
END

Examples

The WHILE loop can be used in a variety of scenarios. Let’s go through some sample cases.

Printing multiple times

Let’s print a string 10 times using a WHILE loop. For that, we need a variable to hold the count, and inside the loop, we increase its value by 1:

Get hands-on with 1200+ tech skills courses.