Here's one way to do it. You'll have to define the "order" of the table. In this example I have a RowID column as the PK. It is seeded at a high number and skips every other number to simulate an actual table with gaps in the IDs. But the concept will work on whatever you unique key is.set nocount onuse pubsgo--create a fake table and add some rowscreate table junk (rowid int identity(300000,2) primary key, i int not null, batchid int null)godeclare @i intset @i = 1while @i < 1511begin insert junk (i) values (@i) set @i = @i+1endgo--Do the BatchID update in batches of 500declare @startRowid int ,@endRowid int ,@batchid intselect @startrowid = min(rowid) ,@endRowid = max(rowid) ,@batchid = 1from (select top 500 rowid from junk order by rowid) awhile @endRowID is not nullbegin update junk set batchid = @batchid where rowid >= @startRowid and rowid <= @endRowid select @startrowid = min(rowid) ,@endRowid = max(rowid) ,@batchid = @batchid + 1 from (select top 500 rowid from junk where rowid > @endRowid order by rowid) a endselect batchid, count(*) [BatchCount] ,min(rowid) startRowid ,max(rowid) endrowidfrom junk group by batchid order by 1godrop table junk
Be One with the OptimizerTG