Sql server while loop statement how to use

Sql server While loop statement in sql Programming:



In this Post we learn about how to use while loop in sql. The SQL is the set of instructions that are used to interact with a database.

SQL SERVER WHILE LOOP:

As we know that loop is iterative statement when we use same code again and again the we use loop. We also learned in Asp.net C# programming that while loop is entry control loop. In Sql here the use of loop is similar only syntax is differing.

Learn how to use the WHILE LOOP in SQL Server with syntax and examples.

WHILE LOOP DESCRIPTION:

In SQL Server, you use a WHILE LOOP when you are not sure how many times you will execute the loop body and the loop body may not execute even once.

SQL WHILE LOOP SYNTAX:

The syntax for the WHILE LOOP in SQL Server is:
WHILE condition
BEGIN
   {.statements.}
END;


Parameter or Arguments in sql:

Condition is the condition is test each pass through the loop. If condition evaluates to TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is terminated.
Statements are the statements of code to execute each pass through the loop.

  • You would use a WHILE LOOP statement when you are unsure of how many times you want the loop body to execute.
  • Since the WHILE condition is evaluated before entering the loop, it is possible that the loop body may not execute even once.

EXAMPLE OF WHILE LOOP IN SQL:

Let's look at an example that shows how to use a WHILE LOOP in SQL Server 

For example:

DECLARE @value INT;
SET @value = 0;
WHILE @value <= 10
BEGIN
   PRINT 'Inside WHILE LOOP';
   SET @value = @value + 1;
END;
PRINT 'Done WHILE LOOP';
GO

  • In this the Sql WHILE LOOP, the loop would terminate once the @value exceeded 10 as specified by:

                                WHILE @value <= 10

  • DECLARE is keyword use for declare a variable in sql and the PRINT is use to display the value in sql console.


Sql Server Related Post:

Asp.net related Post:




Comments