SQL Server loop - how do I loop through a set of records

前端 未结 8 1495
慢半拍i
慢半拍i 2020-11-28 17:54

how do I loop through a set of records from a select?

So say for example I have a few records that I wish to loop through and do something with each record. Here\'s

8条回答
  •  借酒劲吻你
    2020-11-28 18:20

    Small change to sam yi's answer (for better readability):

    select top 1000 TableID
    into #ControlTable 
    from dbo.table
    where StatusID = 7
    
    declare @TableID int
    
    while exists (select * from #ControlTable)
    begin
    
        select @TableID = (select top 1 TableID
                           from #ControlTable
                           order by TableID asc)
    
        -- Do something with your TableID
    
        delete #ControlTable
        where TableID = @TableID
    
    end
    
    drop table #ControlTable
    

提交回复
热议问题