FOR loop in SQL Server

The FOR loop is often used to run a code repeatedly for the number of repetitions. However, in SQL Server there is no FOR loop.

The FOR loop is often used to run a code repeatedly for the number of repetitions. However, in SQL Server there is no FOR loop. However, you can still use the WHILE loop to simulate FOR here. Please follow Quantrimang to see how to use it through the following article.

For loop syntax in SQL Server

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

 DECLARE @cnt INT = 0; 

WHILE @cnt < cnt_total
BEGIN
{.câu lệnh thực thi.}
SET @cnt = @cnt + 1;
END;

Parameters :

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

Example of a for loop in SQL Server

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

 DECLARE @cnt INT = 0; 

WHILE @cnt < 10
BEGIN
PRINT 'Vi du mo phong vong lap FOR trong SQL Server cua TipsMake.com';
SET @cnt = @cnt + 1;
END;

PRINT 'Ket thuc mo phong vong lap FOR cua TipsMake.com';
GO

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

Last lesson: WHILE loop in SQL Server

Next article: BREAK (Control Disconnect) command in SQL Server

4 ★ | 1 Vote