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 :
- cnt_total: Number of loops you want FOR (WHILE) to execute.
- 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
You should read it
Maybe you are interested
What is Large Action Model (LAM)? SpaceX's Crew Dragon spacecraft successfully assembled with the ISS station, completely automated Will NASA partner with Tesla to create the most unprecedented lunar exploration vehicle? SpaceX is about to blow up a tens of millions of dollars worth of boosters on the Atlantic Life is amazing: The process of transforming from a living cell to a perfect living organism in just 6 minutes NASA announces a stunning series of GIF images that capture the historic moments of the aerospace industry