---
title: "How to apply WHILE loop with simple examples in SQL server?"  
description: "How to apply WHILE loop with simple examples in SQL server?"  
author: "Ravi Vishwakarma"  
published: 2023-01-27  
updated: 2023-01-27  
canonical: https://www.mindstick.com/forum/157353/how-to-apply-while-loop-with-simple-examples-in-sql-server  
category: "mssql server"  
tags: ["database", "sql server"]  
reading_time: 1 minute  

---

# How to apply WHILE loop with simple examples in SQL server?

How to [apply](https://www.mindstick.com/articles/13148/discover-to-apply-make-up-like-a-professional-supermodel) `WHILE loop` with [simple](https://yourviews.mindstick.com/story/1469/5-simple-ways-to-stay-fit-amp-healthy) examples in [SQL server](https://www.mindstick.com/articles/12999/what-is-table-valued-function-in-sql-server). I want to [insert data](https://www.mindstick.com/forum/33964/insert-data-in-datagridview-from-text-box-c-sharp) in [table](https://www.mindstick.com/articles/43918/how-to-design-table-using-bootstrap) using loops.

## Replies

### Reply by Amrita Bhattacharjee

```plaintext
DECLARE @count INT;
SET @count = 1;
   
WHILE @count<= 20
BEGIN
   PRINT @count
   SET @count = @count + 1;
END;
```

Above is an example of using WHILE loop in [SQL](https://www.mindstick.com/articles/13115/types-of-keys-in-sql-or-oracle-database) whereas the loop will print the numbers 1 to 20. DECLARE statement here initializes the counter variable. PRINT statement is used to give the output value of the counter which is based on the condition that if the condition is true then only the PRINT statement will give the counter variable value as output. SET statement is used for incrementing the value of counter variable by 1 and the above loop will continue until the value of counter variable meets equal or less than 20 or else until the condition becomes false to end the whole process.


---

Original Source: https://www.mindstick.com/forum/157353/how-to-apply-while-loop-with-simple-examples-in-sql-server

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
