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

When dealing with a relational database management system (RDBMS) like SQL Server, compatibility level is an important concept to understand....
In this blog post, let’s learn about the error message “49975 – Unable to load controller client certificate due to...
In this blog post, let’s learn about the error message “49973 – Cannot remove tempdb remote file to local tempdb...