FOR LOOP in SQL Server?

If you are new to SQL Server and trying to create a stored procedure with some simple logic, you might be looking for the syntax of FOR LOOP. Unfortunately FOR LOOP is not there in SQL Server. The alternative way is to use the WHILE LOOP.

Let us see how to use a WHILE LOOP to mimic for loop logic. Let’s consider that you want to execute one or more SQL statements 5 times, then you have to use the WHILE LOOP like this:

/* 
 If you want to loop for 10 times, then 
*/
DECLARE @i INT = 0;
WHILE @i < 10
BEGIN
   {--- SQL statement or block ---}
   SET @i = @i + 1;
END;
FOR LOOP In SQL Server?

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.