Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey Every one...


Can we write for-loop in SQL server stored procedure. if so pls

give code...if not Please give any alternatives

Thanks,
Posted
Updated 1-May-13 22:48pm
v2

Hi
Yes of course you can write for example

While Loop:

SQL
DECLARE @intFlag INT
SET @i = 1
WHILE (@i <=5)
BEGIN
PRINT @i
SET @i = @i + 1
END
GO


And from here http://stackoverflow.com/questions/4930103/how-to-use-for-loop-in-stored-procedure-sql-server-2005[^] you can find for-loop sample ;)

Best Regards.
 
Share this answer
 
Example of simple while loop(Nothing exist like for loop in stored procedures)

SQL
DECLARE @intFlag INT

SET @count = 1

WHILE (@count <=5)

BEGIN

PRINT @count

SET @count = @count + 1

END

GO
 
Share this answer
 
Comments
cakakanaboina 2-May-13 5:10am    
Thanks...
Thanks7872 2-May-13 5:12am    
you can accept or upvote any answer if it helps.thanks.
SQL does not have a FOR-statement, but you can use WHILE-statement[^] to simulate a for loop.
SQL
SET i = 0;
WHILE (i < 10)
    // Do your stuff

    SET i = i + 1
END
 
Share this answer
 
There is no such thing as a "for" loop in SQL - however there is a WHILE loop, which can do teh same job if you deal with the loop count yourself: MSDN: WHILE[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900