您将需要某种类型的唯一键来匹配每个表中的行。我冒昧地将 TempGuid 列添加到您的每个表(您以后可以删除):
-- Setup test data
declare @Table1 table (
Id int null
, Field1 int not null
, Field2 int not null
, TempGuid uniqueidentifier not null unique
)
insert into @Table1 (Field1, Field2, TempGuid) select 1, 2, newid()
insert into @Table1 (Field1, Field2, TempGuid) select 3, 4, newid()
declare @Table2 table (
Id int not null primary key identity(1, 1)
, Field1 int not null
, Field2 int not null
, TempGuid uniqueidentifier not null unique
)
-- Fill Table2
insert into @Table2 (Field1, Field2, TempGuid)
select Field1, Field2, TempGuid
from @Table1
-- Update Table1 with the identity values from Table2
update a
set a.Id = b.Id
from @Table1 a
join @Table2 b on a.TempGuid = b.TempGuid
-- Show results
select * from @Table1
Output
如果您在 Table1 上已经有一个要插入 Table2 的唯一键,那将是可行的。您还可以在循环或游标中执行临时唯一键(可能再次使用 GUID)并一次处理一行,但这对我来说似乎更糟。
更新
这是在您的表上运行的实际 SQL:
-- Add TempGuid columns
alter table Table1 add TempGuid uniqueidentifier null
update Table1 set TempGuid = newid()
alter table Table2 add TempGuid uniqueidentifier not null
-- Fill Table2
insert into Table2 (Field1, Field2, TempGuid)
select Field1, Field2, TempGuid
from Table1
-- Update Table1 with the identity values from Table2
update a
set a.Id = b.Id
from Table1 a
join Table2 b on a.TempGuid = b.TempGuid
-- Remove TempGuid columns
alter table Table1 drop column TempGuid
alter table Table2 drop column TempGuid