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. 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
4 ★ | 1 Vote
You should read it
May be interested
- ASCII function in SQL Serverthe article will explore and guide you how to use the ascii () function in sql server.
- CHAR function in SQL Serverchar function in sql server is used to convert an integer expression into the corresponding character in ascii code.
- CHARINDEX function in SQL Serverthe charindex function in sql server is used to search for a substring within a large string starting from the specified position.
- CONCAT function in SQL Serverlearn how to use the concat () function in sql server to join two or more strings into a string.
- The '+' operator in SQL Serverlearn how to use the + operator in sql server to join two or more strings into a string.
- DATALENGTH function in SQL Serverthe article will explore and show you how to use the datalength function in sql server to display the number of bytes used to represent an expression ..