Written by
November 20, 2022; Updated: Jan 2023
Loops are the programming concept that enables us to write a few lines of code and repeat them until the loop condition holds.
A SQL WHILE loop is a control-flow statement that allows code to execute repeatedly based on a given Boolean condition. The loop continues until the condition becomes false.
DECLARE @counter INT = 1; -- Initialize counter
WHILE @counter <= 10 -- Condition for the loop
BEGIN
PRINT 'Inside WHILE loop'; -- Code to be executed
SET @counter = @counter + 1; -- Increment counter
END;
PRINT 'Done with WHILE loop';