DECLARE @count INT;
SET @count = 1;
WHILE @count<= 20
BEGIN
PRINT @count
SET @count = @count + 1;
END;
Above is an example of using WHILE loop in SQL whereas the loop will print the numbers 1 to 20. DECLARE statement here initializes the counter variable. PRINT statement is used to give the output value of the counter which is based on the condition that if the condition is true then only the PRINT statement will give the counter variable value as output. SET statement is used for incrementing the value of counter variable by 1 and the above loop will continue until the value of counter variable meets equal or less than 20 or else until the condition becomes false to end the whole process.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Above is an example of using WHILE loop in SQL whereas the loop will print the numbers 1 to 20. DECLARE statement here initializes the counter variable. PRINT statement is used to give the output value of the counter which is based on the condition that if the condition is true then only the PRINT statement will give the counter variable value as output. SET statement is used for incrementing the value of counter variable by 1 and the above loop will continue until the value of counter variable meets equal or less than 20 or else until the condition becomes false to end the whole process.