Home / SQL Server DBMS / BREAK command

SQL Server BREAK command

The Break command is used to exit a loop where the stop condition is unknown, or you want to stop the loop according to a condition you specify and execute the statements following the loop's END statement.

Syntax

To use the BREAK control break statement in SQL Server, we use the following syntax:

BREAK;

There are no parameters or arguments in the BREAK statement.

Notes:

  • You use BREAK to end the WHILE loop early.
  • If there are nested WHILE LOOPs in the code, BREAK will terminate the nearest WHILE loop.

quangcao

Example

DECLARE @Number INT = 1 ;
DECLARE @Total INT = 0 ;
 
WHILE @Number <= 10
BEGIN
IF @NUMBER = 5
BREAK;
ELSE
 SET @Total = @Total + @Number;
 SET @Number = @Number + 1 ;
END

PRINT @Total;
GO

In this example using the BREAK statement, the WHILE loop will end when @Number reaches the value 5.


Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖