What is the syntax of a for
loop in TSQL?
Just to add as no-one has posted an answer that includes how to actually iterate though a dataset inside a loop, you can use the keywords OFFSET FETCH.
Usage
DECLARE @i INT = 0;
SELECT @count= Count(*) FROM {TABLE}
WHILE @i <= @count
BEGIN
SELECT * FROM {TABLE}
ORDER BY {COLUMN}
OFFSET @i ROWS
FETCH NEXT 1 ROWS ONLY
SET @i = @i + 1;
END
T-SQL doesn't have a FOR
loop, it has a WHILE
loop
WHILE (Transact-SQL)
WHILE Boolean_expression
BEGIN
END
While Loop example in T-SQL which list current month's beginning to end date.
DECLARE @Today DATE= GETDATE() ,
@StartOfMonth DATE ,
@EndOfMonth DATE;
DECLARE @DateList TABLE ( DateLabel VARCHAR(10) );
SET @EndOfMonth = EOMONTH(GETDATE());
SET @StartOfMonth = DATEFROMPARTS(YEAR(@Today), MONTH(@Today), 1);
WHILE @StartOfMonth <= @EndOfMonth
BEGIN
INSERT INTO @DateList
VALUES ( @StartOfMonth );
SET @StartOfMonth = DATEADD(DAY, 1, @StartOfMonth);
END;
SELECT DateLabel
FROM @DateList;
There is no for-loop, only the while-loop:
DECLARE @i int = 0
WHILE @i < 20
BEGIN
SET @i = @i + 1
/* do some work */
END
DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=5)
BEGIN
PRINT @intFlag
SET @intFlag = @intFlag + 1
END
GO
Simple answer is NO !!
.
There is no
FOR
in SQL, But you can useWHILE
orGOTO
to achieve the way how theFOR
will work.
WHILE :
DECLARE @a INT = 10
WHILE @a <= 20
BEGIN
PRINT @a
SET @a = @a + 1
END
GOTO :
DECLARE @a INT = 10
a:
PRINT @a
SET @a = @a + 1
IF @a < = 20
BEGIN
GOTO a
END
I always prefer WHILE
over GOTO
statement.