Programming in MS SQL Server 2012

WHILE Statement



WHILE statement is used to define sets of conditions for the repeated execution of an SQL statement or statement block. The statements are executed repeatedly as long as the specified condition is TRUE. The execution of statements in the WHILE loop can be controlled from inside the loop with the BREAK and CONTINUE keywords.
Syntax

-- Syntax --

 

WHILE Boolean_expression

     { sql_statement | statement_block | BREAK | CONTINUE }


Boolean_expression
Boolean_expression is an expression that returns TRUE or FALSE. If the Boolean expression contains a SELECT statement, the SELECT statement must be enclosed in parentheses.
Sql_statement | statement_block
Sql_statement | statement_block is any Transact-SQL statement or statement grouping that defined with BEGIN ... END block.
BREAK
BREAK keyword is used to causes an exit from the innermost WHILE loop statement. Any statements that appear after the END keyword, marking the end of the loop, are executed.
CONTINUE
CONTINUE keyword is used to causes the WHILE loop to restart, ignoring any statements after the CONTINUE keyword.
The following example describes WHILE loop conditional statement.

-- Example 86 --

 

DECLARE @Number int

 

SET @Number = 1

 

WHILE @Number < 5

   BEGIN

      SELECT @Number

      SET @Number = @Number + 1

   END


Query Output Screen

* * * * *


Email Your Comment To AUTHOR