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

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

    I didn't know about the WHILE structure.

    The WHILE structure with a table variable, however, looks similar to using a CURSOR, in that you still have to SELECT the row into a variable based on the row IDENTITY, which is effectively a FETCH.

    Is there any difference between using WHERE and something like the following?

    DECLARE @table1 TABLE ( col1 int )  
    INSERT into @table1 SELECT col1 FROM table2
    
    DECLARE cursor1 CURSOR  
        FOR @table1
    OPEN cursor1  
    FETCH NEXT FROM cursor1
    

    I don't know if that's even possible. I suppose you might have to do this:

    DECLARE cursor1 CURSOR  
        FOR SELECT col1 FROM @table1
    OPEN cursor1  
    FETCH NEXT FROM cursor1
    

    Thanks for you help!

提交回复
热议问题