In this post, you’ll learn how to use FOR Loop in SQL Server with some good examples.
SQL Server does not support FOR LOOP. However, the WHILE LOOP is used to simulate the FOR LOOP and still provide the similar behaviour.
Syntax of WHILE Loop in SQL Server
DECLARE @index INT = 0; DECLARE @limit INT = 10; WHILE @indx < @limit BEGIN /* Your Logic/Statement */ SET @index = @count + 1; END;
Parameters
- @limit – The number of times you want the LOOP to execute.
- @index – Indexer that starts with 0.
Example
DECLARE @index INT = 0; DECLARE @limit INT = 15; WHILE @indx < @limit BEGIN PRINT 'You are at DeveloperPublish.com'; SET @index = @count + 1; END;
In the above example, the simulated For Loop in SQL Server would terminate after executing 15 times