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

后端 未结 11 633
轮回少年
轮回少年 2020-12-04 07:47

Is there anyway to loop through a table variable in T-SQL?

DECLARE @table1 TABLE ( col1 int )  
INSERT into @table1 SELECT col1 FROM table2

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 08:20

    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 table2
    SET @RowsToProcess = @@ROWCOUNT 
    
    WHILE @RowsToProcess > 0 -- Countdown
    BEGIN
        SELECT *
            FROM @table1
            WHERE RowID=@RowsToProcess
    
        --do your thing here--
    
        SET @RowsToProcess = @RowsToProcess - 1; -- Countdown
    END
    

提交回复
热议问题