SQL SERVER – Simple Example of WHILE Loop With CONTINUE and BREAK Keywords

I have tried to explain the usage of simple WHILE loop in first example. BREAK keyword will exit the stop the while loop and control is moved to next statement after the while loop. CONTINUE keyword skips all the statement after its execution and control is sent to first statement of while loop. Run following examples in Query Editor and see the result. This is very easy to understand example.

1. Example of WHILE Loop

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
END
GO

ResultSet:
1
2
3
4
5

2. Example of WHILE Loop with BREAK keyword

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
IF @intFlag = 4
BREAK;
END
GO

ResultSet:
1
2
3

3. Example of WHILE Loop with CONTINUE and BREAK keywords

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
CONTINUE;
IF @intFlag = 4 — This will never executed
BREAK;
END
GO

ResultSet:
1
2
3
4
5

Share this:
Share

7 thoughts on “SQL SERVER – Simple Example of WHILE Loop With CONTINUE and BREAK Keywords

  1. Hello to every one, because I am genuinely eager of reading this website’s post
    to be updated daily. It contains good stuff.

  2. I’ve learn some good stuff here. Certainly price bookmarking for revisiting.
    I surprise how a lot attempt you set to create
    this sort of excellent informative web site.

  3. Hi there this is kinda of off topic but I was wanting to
    know if blogs use WYSIWYG editors or if you have to manually code with HTML.

    I’m starting a blog soon but have no coding expertise so I wanted to
    get advice from someone with experience. Any help would be greatly appreciated!

  4. Hi there just wanted to give you a quick heads up.
    The words in your post seem to be running off the screen in Opera.
    I’m not sure if this is a format issue or something to do with browser compatibility but
    I figured I’d post to let you know. The design look great though!

    Hope you get the issue resolved soon. Many thanks

Leave a Reply

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