22,300
社区成员




update A set A.1 = A.1+B.1,A.2 = A.2+B.2,... from B where A.id=B.id
use tempdb
go
--創建測試表
if object_id('Tb_A') is not null drop table Tb_A
if object_id('Tb_B') is not null drop table Tb_B
create table Tb_A(ID int primary key ,c2 nvarchar(50),c3 nvarchar(50)) --ID作為主鍵
create table Tb_B(ID int primary key ,c2 nvarchar(50),c3 nvarchar(50)) --ID作為主鍵
go
--批量處理使用該字段控制;
alter table Tb_B add Col_Identity int identity(1,1)
go
--插入測試數據
set nocount on
insert into Tb_A(ID,c2,c3) values(1,'c1','c2'),(2,'c3','c4'),(3,'c5','c6')
insert into Tb_B(ID,c2,c3) values(2,'c3_a','c4_a'),(3,'c5_b','c6_b'),(4,'c7','c8')
set nocount off
go
-- 存儲過程內容:
if object_id('up_MoveData_BtoA') is not null drop proc up_MoveData_BtoA
go
create proc up_MoveData_BtoA
As
declare @batch int=2000, --每2000行提交一次,可以根據實際服務器來調整
@For int=1
While 1=1
begin
if Not Exists(select 1 from dbo.Tb_B) break;
Begin Try
Begin Transaction
update a
set a.c2=b.c2,a.c3=b.c3
from Tb_A a
inner join Tb_B b on b.ID=a.ID
and b.Col_Identity between (@For-1)*@batch+1 And @For*@batch
insert into dbo.Tb_A ( ID, c2, c3 )
select ID,c2,c3 from dbo.Tb_B a where not exists(select 1 from dbo.Tb_A y where y.ID=a.ID) and a.Col_Identity between (@For-1)*@batch+1 And @For*@batch
delete Tb_B where Col_Identity between (@For-1)*@batch+1 And @For*@batch
set @For+=1;
Commit Transaction
End Try
Begin Catch
Declare @Error nvarchar(2047)
Set @Error=Error_message()
Raiserror 50001 @Error
Rollback Transaction
goto ExitFlag
End Catch
end
ExitFlag:
go
--調用存儲過程:
exec up_MoveData_BtoA
go