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

后端 未结 5 2106
情书的邮戳
情书的邮戳 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:30

    You can use SET ROWCOUNT { number | @number_var } it limits number of rows processed before stopping the specific query, example below:

    SET ROWCOUNT 10000 -- define maximum updated rows at once
    
    UPDATE XXX SET 
        XXX.YYY = #TempTable.ZZZ
    FROM XXX
    INNER JOIN (SELECT SomeFields ... ) #TempTable ON XXX.SomeId = #TempTable.SomeId
    WHERE XXX.YYY <> #TempTable.ZZZ and OtherConditions
    
    -- don't forget about bellow 
    -- after everything is updated
    SET ROWCOUNT 0
    

    I've added XXX.YYY <> #TempTable.ZZZ to where clause to make sure you will not update twice already updated value.

    Setting ROWCOUNT to 0 turn off limits - don't forget about it.

提交回复
热议问题