---
title: "Problem using loop in sqlserver"  
description: "Problem using loop in sqlserver"  
author: "Somesh"  
published: 2012-01-19  
updated: 2013-04-09  
canonical: https://www.mindstick.com/forum/377/problem-using-loop-in-sqlserver  
category: "mssql server"  
tags: ["mssql server"]  
reading_time: 1 minute  

---

# Problem using loop in sqlserver

Hi\
\
How to use loop in [sqlserver](https://www.mindstick.com/forum/33737/between-condition-in-sqlserver)?\
\
Thanks in [advance](https://www.mindstick.com/blog/33258/jee-mains-and-jee-advance-exams)

## Replies

### Reply by Shankar M

Hi Somesh,\
There is no for loop statement in SQL Server. We use only while statements for Looping. Lets havea look at this example.\
DECLARE @I INT -- Declaring a Local VariableSET @I =0 -- Assigning a Default Value to Local VariableWHILE @I <=5 -- Start of the Loop, Evaluates until @I turns to be less than or equal to 5 BEGIN PRINT 'I value is :' + CAST(@I AS VARCHAR(10)) -- Displaying the Present @I value SET @I = @I + 1 -- Incrementing the @I valueEND -- End of Loop \
Thanks,Shankar

### Reply by Amit Singh

Hi somesh,\
\
This is the sample code for using loop in sqlserver\
\

```
Declare @maxNo intDeclare @i intset @maxNo=4set @i=1print 'Output'---Use while loop----while(@i<=@maxNo)begin                    print @i    set @i=@i+1end   
```

\
----Output-------\
1\
2\
3\
4


---

Original Source: https://www.mindstick.com/forum/377/problem-using-loop-in-sqlserver

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
