SQL WHILE Loop Syntax and Example
SQL WHILE Loop Syntax and Example
example
The syntax of the WHILE loop in SQL looks like as follows:
WHILE condition
BEGIN
{...statements...}
END
After these explanations, we will give a very simple example of a WHILE loop
in SQL. In the example given below, the WHILE loop example will write a value
of the variable ten times, and then the loop will be completed:
DECLARE @Counter INT
SET @Counter=1
WHILE ( @Counter <= 10)
BEGIN
PRINT 'The counter value is = ' +
CONVERT(VARCHAR,@Counter)
SET @Counter = @Counter + 1
END
Break Statement
BREAK statement is used in the SQL WHILE loop in
order to exit the current iteration of the loop
immediately when certain conditions occur. In the
generally IF…ELSE statement is used to check
whether the condition has occurred or not.
• DECLARE @Counter INT
• SET @Counter=1
• WHILE ( @Counter <= 10)
• BEGIN
• PRINT 'The counter value is = ' +
CONVERT(VARCHAR,@Counter)
• IF @Counter >=7
• BEGIN
• BREAK
• END
Continue Statement
CONTINUE statement is used in the SQL WHILE loop in order to stop the current
iteration of the loop when certain conditions occur, and then it starts a new
iteration from the beginning of the loop. Assume that we want to write only even
numbers in a WHILE loop. In order to overcome this issue, we can use the
CONTINUE statement. In the following example, we will check whether the variable
value is odd or even. If the variable value is odd, the code enters the IF…ELSE
statement blocks and increment the value of the variable, execute the
CONTINUE statement and starts a new iteration:
CONTINUE statement