How to break a WHILE loop in SQL Server: Explained with Examples

SQL Server break while loop featured image
Reading Time: 2 minutes

The task of breaking a WHILE loop in Microsoft SQL Server is very simple.



We basically break a while loop when we want to terminate the loop early. That is, earlier than the loop would have ended if left to it’s natural progression.

To break a WHILE loop early, just use the BREAK keyword!

Take a look at this very simple example:

SQL Server WHILE loop example 3

We have a WHILE loop that simply prints the value of a counter variable as we go through the loop. Once the counter variable is above 8, we end the loop by using the BREAK keyword. The code resumes at the first line after the WHILE loop.

Here’s the output if we run this code:

sql server break while loop running

Nice! Imagine if we didn’t have the IF block in place to check if we need to break out of the loop. Since the condition in the WHILE loop is (@counter < 50), we would have ran through this loop a total of 50 times. But again, that didn’t happen because we have code to check if we should break out of the loop early!



Next steps:

Leave a comment if you found this tutorial helpful!

Do you know how a WHILE loop works in SQL Server? Click the link to find out!

Don’t forget about another very helpful decision structure:

SQL IF EXISTS Decision Structure: Explained with Examples

Thank you very much for reading!



Make sure you subscribe to my newsletter to receive special offers and notifications anytime a new tutorial is released!

If you have any questions, please leave a comment. Or better yet, send me an email!

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *