SQL Server: FOR LOOP

FOR LOOP in SQL Server

Learn how to simulate the FOR LOOP in SQL Servers (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 LOOPS 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 Servers (Transact-SQL) is:

DECLARE @cnt INT = 0;

WHILE @cnt < cnt_total
BEGIN
   {...statements...}
   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 Servers (Transact-SQL) using the WHILE LOOP.

Example

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

For example:

DECLARE @cnt INT = 0;

WHILE @cnt < 10
BEGIN
   PRINT 'Inside simulated FOR LOOP on adglob.in';
   SET @cnt = @cnt + 1;
END;

PRINT 'Done simulated FOR LOOP on adglob.in';
GO

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

Leave a Reply