What is the syntax of a for
loop in TSQL?
How about this:
BEGIN
Do Something
END
GO 10
... of course you could put an incremental counter inside it if you need to count.
Try it, learn it:
DECLARE @r INT = 5
DECLARE @i INT = 0
DECLARE @F varchar(max) = ''
WHILE @i < @r
BEGIN
DECLARE @j INT = 0
DECLARE @o varchar(max) = ''
WHILE @j < @r - @i - 1
BEGIN
SET @o = @o + ' '
SET @j += 1
END
DECLARE @k INT = 0
WHILE @k < @i + 1
BEGIN
SET @o = @o + ' *' -- '*'
SET @k += 1
END
SET @i += 1
SET @F = @F + @o + CHAR(13)
END
PRINT @F
With date:
DECLARE @d DATE = '2019-11-01'
WHILE @d < GETDATE()
BEGIN
PRINT @d
SET @d = DATEADD(DAY,1,@d)
END
PRINT 'n'
PRINT @d
For loop is not officially supported yet by SQL server. Already there is answer on achieving FOR Loop's different ways. I am detailing answer on ways to achieve different types of loops in SQL server.
DECLARE @cnt INT = 0;
WHILE @cnt < 10
BEGIN
PRINT 'Inside FOR LOOP';
SET @cnt = @cnt + 1;
END;
PRINT 'Done FOR LOOP';
If you know, you need to complete first iteration of loop anyway, then you can try DO..WHILE or REPEAT..UNTIL version of SQL server.
DECLARE @X INT=1;
WAY: --> Here the DO statement
PRINT @X;
SET @X += 1;
IF @X<=10 GOTO WAY;
DECLARE @X INT = 1;
WAY: -- Here the REPEAT statement
PRINT @X;
SET @X += 1;
IFNOT(@X > 10) GOTO WAY;
Reference