T-SQL: How to Generate Numbers from 1 to 10 Using a WHILE Loop – SQL Circuit

T-SQL: How to Generate Numbers from 1 to 10 Using a WHILE Loop

DECLARE @Min INT = 1, @Max INT = 10;
DECLARE @Result TABLE (ID INT);

WHILE @Min <= @Max
BEGIN
    INSERT INTO @Result VALUES (@Min);
    SET @Min = @Min + 1;
END

SELECT * FROM @Result;

Here’s the sequential breakdown of above SQL query execution flow:

  • Variables @Min and @Max are initialized with values 1 and 10.
  • A table variable @Result is declared to hold integer values.
  • The WHILE loop begins, checking if @Min is less than or equal to @Max.
  • Each loop iteration inserts the current @Min value into @Result.
  • @Min is incremented by 1 to move toward the termination condition.
  • Loop continues until @Min exceeds @Max.
  • Final SELECT retrieves and displays all inserted values from @Result.

Leave a Reply

Your email address will not be published. Required fields are marked *