Home > DeveloperSection > Forums > Problem using loop in sqlserver
Somesh

Total Post:21

Points:147
Posted on    January-19-2012 1:24 AM

 MSSQL Server MSSQL Server 
Ratings:


 2 Reply(s)
 1188  View(s)
Rate this:
Hi

How to use loop in sqlserver?

Thanks in advance


Amit Singh

Total Post:103

Points:721
Posted on    January-19-2012 1:33 AM

Hi somesh,

This is the sample code for using loop in sqlserver

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

----Output-------
1
2
3
4

Shankar M

Total Post:25

Points:175
Posted on    April-09-2013 9:29 PM

Hi Somesh,

There is no for loop statement in SQL Server. We use only while statements for Looping. Lets have
a look at this example.

DECLARE @I INT -- Declaring a Local Variable
SET @I =0      -- Assigning a Default Value to Local Variable
WHILE @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 value
END            -- End of Loop 

Thanks,
Shankar

Don't want to miss updates? Please click the below button!

Follow MindStick