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

后端 未结 11 643
轮回少年
轮回少年 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:08

    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  int
    DECLARE @CurrentRow     int
    DECLARE @SelectCol1     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
    
    SET @CurrentRow=0
    WHILE @CurrentRow<@RowsToProcess
    BEGIN
        SET @CurrentRow=@CurrentRow+1
        SELECT 
            @SelectCol1=col1
            FROM @table1
            WHERE RowID=@CurrentRow
    
        --do your thing here--
    
    END
    

提交回复
热议问题