T-SQL Tutorial

BREAK


In SQL Server, the BREAK command executes and exits a WHILE statement. If there are multiple nested loops, BREAK only exits the current loop. The BREAK statement is usually used inside a WHILE statement.


Syntax

WHILE Boolean_expression
{ sql_statements | transact_sql_statement | BREAK }


Example of BREAK inside WHILE

The example below uses the BREAK statement inside a WHILE statement. In the body of WHILE statement, the @count variable is incremented by 1 at each iteration. When @count will have the value 4, the BREAK statement is used to exit from WHILE statement.

USE model
GO
DECLARE @count int
SET @count = 1
WHILE @count < 5
BEGIN
PRINT 'Test'
SET @count = @count + 1
IF @count = 4
BREAK;
END;
GO