Thursday, September 2, 2010

Simple Example of WHILE Loop With CONTINUE and BREAK Keywords in SQL SERVER 2008.

SQL Server While statement sets a condition for the repeated execution of an SQL statement or statement block. The SQL statements are executed repeatedly as long as the specified condition is return TRUE. The WHILE loop can be controlled from inside the loop with the CONTINUE, and BREAK keywords.


BREAK: - Statement will exit you from the currently processing WHILE loop.
CONTINUE: - Statement will skips executing the rest of the statements between the CONTINUE statement and the END statement of the current loop and starts executing at the first line of the current WHILE loop.

WHILE Syntax
WHILE Boolean_expression
{ Sql Statement Block }

a) Following is simple example of WHILE Loop.

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=10)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
END

Following Result shown.

b) Example of WHILE Loop with BREAK keyword.

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=10)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
IF @intFlag = 7
BREAK;
END

Following Result shown.

c) Example of WHILE Loop with CONTINUE and BREAK keywords.

DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=12)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
CONTINUE;
IF @intFlag = 10
BREAK;
END
Following Result shown.

1 comment:

vijay said...

very nice article

Recent Posts