Sql批量更新

时间:2016-10-03 21:12:54

标签: sql sql-server sql-server-2012

更新sql server中的表以便在一个事务中放置10k记录的限制的最有效方法是什么?

我通过在while循环中添加它来阅读top和ROWCOUNT方法。哪个更有效?或者,如果你知道其他有效方法,请分享。谢谢。

2 个答案:

答案 0 :(得分:0)

以下是一种不使用set rowcount

的潜在方法
-- prepare test data
use tempdb
drop table dbo.t;
create table dbo.t (a int identity, b int)
go
insert into dbo.t ( b)
values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11);
go

-- assume we do 3 records per time, put 10000 here if you wnat 10K records
-- also the update is just to update column [b] to [b] * 2, here is the code

declare @N int = 3; -- do a batch of @N records

declare @i int = 0, @max_loop int;

select @max_loop = count(*)/@N from dbo.t

-- the first batch may include records <= @N-1 and the last batch may include records <= @N
while (@i <= @max_loop)
begin

    ; with c as (
    select rnk=ROW_NUMBER() over (order by a)/@N, a, b from dbo.t
    )
    update c set b = b*2 -- doule b
    where rnk = @i;

    set @i = @i + 1;
end
go
-- check the result
select * from dbo.t

答案 1 :(得分:-1)

您可以尝试以下方法:

WHILE (1=1)
BEGIN
   BEGIN TRANSACTION
  UPDATE TOP (10000)  XXX
     SET XXX.YYY = <ValueToUpdate>
    FROM XXX   -- Update 10000 nonupdated rows
   WHERE <condition> -- make sure that condition makes sure that it does not become infinite loop
   IF @@ROWCOUNT = 0
   BEGIN
      COMMIT TRANSACTION
      BREAK
   END
   COMMIT TRANSACTION
END

修改

更新组织的所有员工,并确保它不会成为infinte循环。在这里,我正在为员工记录更新modifiedDate。

DECLARE @updatedids table(id int)
WHILE (1=1)
BEGIN
   BEGIN TRANSACTION
  UPDATE TOP(10000)  a    
     SET a.ModifiedDate = GETDATE()
   OUTPUT inserted.BusinessEntityID INTO @updatedids
    FROM HumanResources.Employee  a
LEFT JOIN @updatedids u
    ON a.BusinessEntityID = u.id
    WHERE u.id IS NULL 
  -- Update 10000 nonupdated rows
   IF @@ROWCOUNT = 0
   BEGIN
      COMMIT TRANSACTION
      BREAK
   END
   COMMIT TRANSACTION
END