T-SQL WHILE Statement

The WHILE statement in Transact-SQL (T-SQL) is used to execute a set of Transact-SQL statements repeatedly as long as a specified condition is true.

Syntax

WHILE boolean_expression
    sql_statements

Explanation

How it Works

The WHILE loop first evaluates the boolean_expression. If the expression evaluates to TRUE, the sql_statements within the loop are executed. After the statements are executed, the boolean_expression is evaluated again. This process repeats until the boolean_expression evaluates to FALSE. Once the expression is FALSE, the loop terminates, and execution continues with the statement following the WHILE loop.

Key Concepts and Control Flow

Example Usage

Basic Example: Counting

This example demonstrates a simple counter that increments until it reaches a certain value.

DECLARE @Counter INT;
SET @Counter = 1;

WHILE @Counter <= 5
BEGIN
    PRINT 'Counter is: ' + CAST(@Counter AS VARCHAR(10));
    SET @Counter = @Counter + 1;
END;
PRINT 'Loop finished.';

Example with BREAK

This example shows how to use BREAK to exit a loop early based on a specific condition.

DECLARE @Value INT;
SET @Value = 10;

WHILE 1 = 1 -- Infinite loop, but we'll break out
BEGIN
    PRINT 'Current value: ' + CAST(@Value AS VARCHAR(10));
    SET @Value = @Value - 1;

    IF @Value < 5
    BEGIN
        PRINT 'Value is less than 5, breaking loop.';
        BREAK; -- Exit the WHILE loop
    END
END;
PRINT 'Loop exited using BREAK.';

Example with CONTINUE

This example illustrates using CONTINUE to skip processing for certain loop iterations.

DECLARE @Number INT;
SET @Number = 0;

WHILE @Number < 10
BEGIN
    SET @Number = @Number + 1;

    IF @Number % 2 = 0 -- If the number is even
    BEGIN
        PRINT 'Skipping even number: ' + CAST(@Number AS VARCHAR(10));
        CONTINUE; -- Skip to the next iteration
    END

    PRINT 'Processing odd number: ' + CAST(@Number AS VARCHAR(10));
END;
PRINT 'Loop finished.';

Important Considerations

The WHILE statement is a powerful tool for procedural logic within T-SQL. Use it judiciously for tasks that require iterative execution.