且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在单个更新语句中在SQL Server中进行批量更新

更新时间:2022-11-27 23:13:44

我创建了一些超过1m记录的虚拟数据

I created some dummy data with over 1m records
Create table company
(
	Id int identity(1,1),
	[Name] nvarchar(50),
	Address1 nvarchar(50),
	Address2 nvarchar(50),
	Address3 nvarchar(50),
	ZipPostCode nvarchar(20),
	Country nvarchar(50)
	-- and whatever else you need
)
GO
insert into company ([Name]) values ('dummy')
GO 1000
go
INSERT INTO company ([Name]) SELECT [Name] FROM company
go 6




I then created a temporary table with one record for each of the records in company, just the Id and the current name

select Id, [Name] into #temp from Company



我使用新名称更新了临时表 - 相当快,只有2列,例如


I updated the temporary table with the new name(s) - reasonably quick as only 2 columns e.g.

update #temp set [Name] = [Name] + cast(Id as varchar)



要更新原始版本,请使用连接 - 它更快


To update the original use a join - it's faster

update A
set [Name] = T.[Name]
FROM company A
INNER JOIN #temp T on A.Id = T.Id

我的笔记本电脑花了大约2分钟来处理140万而没有大量可用内存。我希望设置一半的服务器能够占用一半的时间

It took my laptop around 2 minutes to process 1.4 million with not a lot of memory available. I'd expect a half decent server set up to take half that time