Example of WHILE Loop in SQL Server

Here is a simple example of WHILE Loop in SQL Server:

DECLARE @counter1 INT
SET @counter1 = 1
WHILE (@counter1 < 6) BEGIN PRINT @counter1 SET @counter1 = @counter1 + 1 END GO

while_loop_sql_server

You can use BREAK and CONTINUE statements with IF...ELSE to control the execution of the WHILE loop:

DECLARE @counter1 INT
SET @counter1 = 1
WHILE (@counter1 < 6) BEGIN PRINT @counter1 SET @counter1 = @counter1 + 1 IF @counter1 = 3 BREAK ELSE CONTINUE END GO

while_loop_break_continue_sql_server

If the post helped you, please share it:
Pin It

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">