ASP.NET,C#.NET,VB.NET,JQuery,JavaScript,Gridview,SQL Server,Ajax,jQuery Plugins,jQuery UI,SSRS,XML,HTML,jQuery demos,code snippet examples.

Breaking News

  1. Home
  2. sql
  3. How to use while loop in SQL statement?

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.
Example of WHILE Loop in SQL
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
Example of WHILE Loop with BREAK keyword
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
Example of WHILE Loop with CONTINUE keyword
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

No comments