How to use while loop in SQL statement?
This article describes about SQL While Loop and how to use it? Summary of the article:
- What is While Loop?
- Example of WHILE Loop in SQL
- Example of WHILE Loop with BREAK keyword
- Example of WHILE Loop with CONTINUE keyword
What is While Loop?
While loop is one kind of loop statement used in SQL.
While loop is one kind of loop statement used in SQL.
Example of WHILE Loop in SQL
SQL While loop example is given bellow:
SQL While loop example is given bellow:
DECLARE @StartPointer INT SET @StartPointer = 1 WHILE (@StartPointer <=5) BEGIN PRINT @StartPointer SET @StartPointer = @StartPointer + 1 END
Result:
1
2
3
4
5
1
2
3
4
5
Example of WHILE Loop with BREAK keyword
SQL While loop example with Break Keyword is given bellow:
SQL While loop example with Break Keyword is given bellow:
DECLARE @StartPointer INT SET @StartPointer = 1 WHILE (@StartPointer <=5) BEGIN PRINT @StartPointer SET @StartPointer = @StartPointer + 1 IF(@StartPointer=3) BREAK END
Result:
1
2
1
2
Example of WHILE Loop with CONTINUE keyword
SQL While loop example with Continue keyword is given bellow:
SQL While loop example with Continue keyword is given bellow:
DECLARE @StartPointer INT SET @StartPointer = 1 WHILE (@StartPointer <=5) BEGIN PRINT @StartPointer SET @StartPointer = @StartPointer + 1 CONTINUE IF(@StartPointer=3) BREAK --This statement will never executed END
Result:
1
2
3
4
5
1
2
3
4
5
No comments