Quantcast
Channel: .Net Core | MVC | HTML Agility Pack | SQL | Technology Crowds
Viewing all articles
Browse latest Browse all 544

while loop in ms sql

$
0
0


We are trying to use While loop in MS SQL Server, in simple While loop and also in break statement when we use while loop.
Try the following goodies to take the hunt.

DECLARE @COUNT INT
SET @COUNT = 1;
WHILE @COUNT < = 4
BEGIN
SET @COUNT = @COUNT+1;
PRINT @COUNT;
END


Result Set:
1
2
3
4


2) Example of WHILE Loop with BREAK keyword
DECLARE @Count INT
SET @Count = 1
WHILE (@Count <=5)
BEGIN
PRINT @Count
SET @Count = @Count + 1
IF @Count = 4
BREAK;
END
GO

ResultSet:
1
2
3


3) Example of WHILE Loop with CONTINUE and BREAK keywords
DECLARE @Count INT
SET @Count = 1
WHILE (@Count <=5)
BEGIN
PRINT @Count
SET @Count = @Count + 1
CONTINUE;
IF @Count = 4 -- This will never executed
BREAK;
END
GO

ResultSet:
1
2
3
4
5


Relevant Reading:

Viewing all articles
Browse latest Browse all 544

Trending Articles