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

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

    DECLARE @table1 TABLE (
        idx int identity(1,1),
        col1 int )
    
    DECLARE @counter int
    
    SET @counter = 1
    
    WHILE(@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 + 1
    END
    

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

提交回复
热议问题