-->

FOR loop in SQL Server

The FOR loop is often used to run a code snippet repeatedly in case of a number of iterations. However, in SQL Server there is no FOR loop. However, you can still use the WHILE loop to simulate FOR here. Follow Quantrimang using the following article.

Syntax

To simulate the FOR loop in SQL Server, we use the following syntax:

DECLARE @cnt INT = 0;

WHILE @cnt & lt; cnt_total
BEGIN
& nbsp; {... statement executed ...}
& nbsp; SET @cnt = @cnt + 1;
END;

Parameters:

  • cnt_total: Number of loops you want FOR (WHILE) to execute.
  • Executable statements: Commands are executed each time through the loop

For example

Consider an example of how to simulate FOR LOOP in SQL Server (Transact-SQL) with WHILE LOOP.

DECLARE @cnt INT = 0;

WHILE @cnt <10
BEGIN
  PRINT 'Reusing the FOR lap in SQL Server's SQL Server';
  SET @cnt = @cnt + 1;
END;

PRINT 'Schedule for Heavendownload.com';
GO

In the example using this WHILE command, the loop will terminate when @cnt reaches the value of 10.

Tôi xây dựng Blog này với niềm hi vọng đem lại thông tin hữu ích cho mọi người.