FOR Loop in SQL Server

In this post, you’ll learn how to use FOR Loop in SQL Server with some good examples.

SQL Server does not support FOR LOOP. However, the WHILE LOOP is used to simulate the FOR LOOP and still provide the similar behaviour.

Syntax of WHILE Loop in SQL Server

DECLARE @index INT = 0;
DECLARE @limit INT = 10;
WHILE @indx < @limit
BEGIN
   /* Your Logic/Statement */
   SET @index = @count + 1;
END;

Parameters

  • @limit – The number of times you want the LOOP to execute.
  • @index – Indexer that starts with 0.

Example

DECLARE @index INT = 0;
DECLARE @limit INT = 15;
WHILE @indx < @limit
BEGIN
   PRINT 'You are at DeveloperPublish.com';
   SET @index = @count + 1;
END;

In the above example, the simulated For Loop in SQL Server would terminate after executing 15 times

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this blog post, let’s learn about the error message “1459 – An error occurred while accessing the database mirroring...
In this blog post, let’s learn about the error message “7937 – Columnstore index has one or more missing column...