Sunday, 23 March 2014

WHILE Loop With CONTINUE and BREAK Keywords in SQL SERVER

The break command terminates the loop, while continue causes a jump to the next iteration of the loop, skipping all the remaining code in that particular loop cycle.

Example of while Loop without break and continue:-

DECLARE @counter INT
SET @counter = 1
WHILE (@counter <=6)
BEGIN
PRINT @counter
SET @counter = @counter + 1
END
GO
Output:-  1  2  3  4  5  6


Example of while Loop with break:-

DECLARE @counter INT
SET @counter = 1
WHILE (@counter <=6)
BEGIN
PRINT @counter
SET @counter = @counter + 1
IF @counter = 3
BREAK;
END
GO
Output:-  1  2 (Because when counter reach on break command fire and terminate the loop, as i told you in definition)
 


Example of while Loop with break and continue:-
DECLARE @counter INT
SET @counter = 1
WHILE (@counter <=6)
BEGIN
PRINT @counter
SET @counter = @counter + 1
CONTINUE;
IF @counter = 5
BREAK;
END
GO
Output:-  1  2  3  4  5  6 (if you are thinking output should be 1 2 3 4, you are wrong because in the last example break would never executed. The reason behind that, every time continue  fired which forced to skip all remaining code for that particular cycle)


That’s it!!…..Happy Programming...

No comments:

Post a Comment