Summary: in this tutorial, you will learn how to use the SQL Server CONTINUE statement to control the flow of the loop.
Introduction to the SQL Server CONTINUE statement #
The CONTINUE statement stops the current iteration of the loop and starts the new one. The following illustrates the syntax of the CONTINUE statement:
WHILE Boolean_expression
BEGIN
-- code to be executed
IF condition
CONTINUE;
-- code will be skipped if the condition is met
END
Code language: SQL (Structured Query Language) (sql)In this syntax, the current iteration of the loop is stopped once the condition evaluates to TRUE. The next iteration of the loop will continue until the Boolean_expression evaluates to FALSE.
Similar to the BREAK statement, the CONTINUE statement is often used in conjunction with an IF statement. Note that this is not mandatory though.
SQL Server CONTINUE example #
The following example illustrates how the CONTINUE statement works.
DECLARE @counter INT = 0;
WHILE @counter < 5
BEGIN
SET @counter = @counter + 1;
IF @counter = 3
CONTINUE;
PRINT @counter;
END
Code language: SQL (Structured Query Language) (sql)Here is the output:
1
2
4
5
Code language: SQL (Structured Query Language) (sql)In this example:
- First, we declared a variable named
@counterand set its value to zero. - Then, the
WHILEloop started. Inside theWHILEloop, we increased the counter by one in each iteration. If the@counterwas three, we skipped printing out the value using theCONTINUEstatement. That’s why in the output, you do not see the number three is showing up.
In this tutorial, you have learned how to use the SQL Server CONTINUE statement to skip the current loop iteration and continue the next.