Header add

In this article we will learn how to use WHILE LOOP in SQL Server.

The WHILE statement as used in various programming languages works in similar way in SQL Server. It is a control flow statement and it is used to perform iterations until the condition holds TRUE.

Syntax

Below are the syntax of WHILE LOOP in SQL Server. It consists of a Boolean Expression which needs to be TRUE in order to execute the WHILE LOOP.

The Statements to be executed will lie between the BEGIN and END keywords.



Example While Loop

Here we did a simple example of Variable count incremental.

Output

While loop in sql server


BREAK statement in WHILE LOOP

Example

In the following example, the print will execute until the @Count variable value is less than 10. But here, when the @Count variable value is 7, then the WHILE LOOP is stopped using the BREAK statement.


While loop using break statement

CONTINUE statement in WHILE LOOP

Example

In the following example, the name will never be printed as the CONTINUE statement ignores the statements after it.

While loop with Continue Statement
You can see as we are using CONTINUE statement so it doesn't print the last statement.

Summary:

That's it on this article hope it clear the examples of While Loop in SQL Server. If you have any suggestion then please write to us.

Post a Comment

Previous Post Next Post