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

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

    Here's another answer, similar to Justin's, but doesn't need an identity or aggregate, just a primary (unique) key.

    declare @table1 table(dataKey int, dataCol1 varchar(20), dataCol2 datetime)
    declare @dataKey int
    while exists select 'x' from @table1
    begin
        select top 1 @dataKey = dataKey 
        from @table1 
        order by /*whatever you want:*/ dataCol2 desc
    
        -- do processing
    
        delete from @table1 where dataKey = @dataKey
    end
    

提交回复
热议问题