Sql Server For Loop

SQL Server: FOR LOOP

Learn how to simulate the FOR LOOP in SQL Server (Transact-SQL) with syntax and examples.

TIP: Since the FOR LOOP does not exist in SQL Server, this page describes how to simulate a FOR LOOP using a WHILE LOOP.

Description

In SQL Server, there is no FOR LOOP. However, you simulate the FOR LOOP using the WHILE LOOP.

Syntax

The syntax to simulate the FOR Loop in SQL Server (Transact-SQL) is:

DECLARE @cnt INT = 0;

WHILE @cnt  <strong>cnt_total</strong>
BEGIN
   <strong>{...statements...}</strong>
   SET @cnt = @cnt + 1;
END;

Parameters or Arguments

cnt_total

The number of times that you want the simulated FOR LOOP (ie: WHILE LOOP) to execute.

statements

The statements of code to execute each pass through the loop.

Note

  • You can simulate the FOR LOOP in SQL Server (Transact-SQL) using the WHILE LOOP.

Example

Let's look at an example that shows how to simulate the FOR LOOP in SQL Server (Transact-SQL) using the WHILE LOOP.

For example:

DECLARE @cnt INT = 0;

WHILE @cnt  10
BEGIN
   PRINT 'Inside simulated FOR LOOP on AODBA.com';
   SET @cnt = @cnt + 1;
END;

PRINT 'Done simulated FOR LOOP on AODBA.com';
GO

In this WHILE LOOP example, the loop would terminate once @cnt reaches 10.