While Statement
If the expression is true, the statement is executed, and then the expression is evaluated again to determine if the statement should be executed again. This process repeats until the expression evaluates to false.
Syntax
The While loop syntax is as defined below:
WHILE bool_exp
{sql_statement}
[BREAK]
{sql_statement}
[CONTINUE]
In the preceding syntax if the bool_exp value is true then sql_statement will be executed. This process repeats until the expression evaluates to false.
Example
-- While statement
print 'While statement'
DECLARE @countnumber varchar(50)
SET @countnumber = 1
WHILE (@countnumber<=30)
BEGIN
PRINT 'Number=' + @countnumber
SET @countnumber = @countnumber + 3
END
The execution of statements in the WHILE loop can be controlled from inside the loop with the break and continue keywords.
BREAK Keyword
Break forces a loop to exit immediately. Suppose we repeat a number from 1 to 20. The loop will go through all the numbers. We want to exit when we get to the number 11 in the loop. That can be done simply by using the break keyword with a while loop.
Example
-- While Statement with Beak
print 'While Statement with break'
DECLARE @countnumber varchar(50)
SET @countnumber = 1
WHILE (@countnumber<=30)
BEGIN
PRINT 'Number=' + @countnumber
SET @countnumber = @countnumber + 3
if(@countnumber=22)
break
END
Continue Keyword
This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code. The continue statement skips the value and jumps to the while loop without terminating the loop.
print 'While Statement with continue'
DECLARE @countnumber varchar(50)
SET @countnumber = 1
WHILE (@countnumber<=30)
BEGIN
PRINT 'Number=' + @countnumber
SET @countnumber = @countnumber + 3
CONTINUE;
if(@countnumber=4) -- This will never execute.
break
END
Output of the preceding examples in SQL Server Management Studio
Now run the preceding examples in SQL Server Management Studio.
-- While statement
print 'While statement'
DECLARE @countnumber varchar(50)
SET @countnumber = 1
WHILE (@countnumber<=30)
BEGIN
PRINT 'Number=' + @countnumber
SET @countnumber = @countnumber + 3
END
go
-- While Statement with Beak
print 'While Statement with break'
DECLARE @countnumber varchar(50)
SET @countnumber = 1
WHILE (@countnumber<=30)
BEGIN
PRINT 'Number=' + @countnumber
SET @countnumber = @countnumber + 3
if(@countnumber=22)
break
END
go
-- While Statement with continue
print 'While Statement with continue'
DECLARE @countnumber varchar(50)
SET @countnumber = 1
WHILE (@countnumber<=30)
BEGIN
PRINT 'Number=' + @countnumber
SET @countnumber = @countnumber + 3
CONTINUE;
if(@countnumber=4) -- This will never execute.
break
END