» Documentation » SQL Reference

While

Repeats execution of SQL statements inside a BEGIN and END block. The statement stop execute when condition is false or executed BREAK command.

Syntax

WHILE Boolean_expression
BEGIN
     sql_statements
     [ BREAK ]
     [ CONTINUE ]
END
BREAK 

Causes an exit from the innermost WHILE loop. Any statements that appear after the END keyword, marking the end of the loop, are executed.

CONTINUE

Causes the WHILE loop to restart, ignoring any statements after the CONTINUE keyword.

Example

declare @id int = 1000, @it int = 0
while @id > 0 and @it <> 500
begin
    set @id = @id-1
    set @it = @id
end

select @id as 'id', @it as 'it'