Can I loop through a table variable in T-SQL? Can I loop through a table variable in T-SQL? sql sql

Can I loop through a table variable in T-SQL?


Add an identity to your table variable, and do an easy loop from 1 to the @@ROWCOUNT of the INSERT-SELECT.

Try this:

DECLARE @RowsToProcess  intDECLARE @CurrentRow     intDECLARE @SelectCol1     intDECLARE @table1 TABLE (RowID int not null primary key identity(1,1), col1 int )  INSERT into @table1 (col1) SELECT col1 FROM table2SET @RowsToProcess=@@ROWCOUNTSET @CurrentRow=0WHILE @CurrentRow<@RowsToProcessBEGIN    SET @CurrentRow=@CurrentRow+1    SELECT         @SelectCol1=col1        FROM @table1        WHERE RowID=@CurrentRow    --do your thing here--END


DECLARE @table1 TABLE (    idx int identity(1,1),    col1 int )DECLARE @counter intSET @counter = 1WHILE(@counter < SELECT MAX(idx) FROM @table1)BEGIN    DECLARE @colVar INT    SELECT @colVar = col1 FROM @table1 WHERE idx = @counter    -- Do your work here    SET @counter = @counter + 1END

Believe it or not, this is actually more efficient and performant than using a cursor.


My two cents.. From KM.'s answer, if you want to drop one variable, you can do a countdown on @RowsToProcess instead of counting up.

DECLARE @RowsToProcess  int;DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), col1 int )  INSERT into @table1 (col1) SELECT col1 FROM table2SET @RowsToProcess = @@ROWCOUNT WHILE @RowsToProcess > 0 -- CountdownBEGIN    SELECT *        FROM @table1        WHERE RowID=@RowsToProcess    --do your thing here--    SET @RowsToProcess = @RowsToProcess - 1; -- CountdownEND