How can I do a SQL UPDATE in batches, like an Update Top?

后端 未结 5 2123
情书的邮戳
情书的邮戳 2020-12-31 02:39

Is it possible to add a TOP or some sort of paging to a SQL Update statement?

I have an UPDATE query, that comes down to something like this:

         


        
5条回答
  •  一个人的身影
    2020-12-31 03:21

    You can do something like the following

    declare @i int = 1
    while @i <= 10 begin
    
        UPDATE  top (10) percent
                masterTable set colToUpdate = lt.valCol
        from    masterTable as mt
                inner join lookupTable as lt
                        on mt.colKey = lt.colKey
        where colToUpdate is null
    
        print @i
        set @i += 1
    end
    
    --one final update without TOP (assuming lookupTable.valCol is mostly not null)
    UPDATE  --top (10) percent
            masterTable set colToUpdate = lt.valCol
    from    masterTable as mt
            inner join lookupTable as lt
                    on mt.colKey = lt.colKey            
    where colToUpdate is null
    

提交回复
热议问题