我需要将 2 个表中的数据合并到第三个表中(都具有相同的模式)并生成旧标识值到新标识值的映射。显而易见的方法是使用游标遍历源表,沿途插入新旧标识值。有没有更好的(可能是面向集合的)方法来做到这一点?
更新:另外一点信息:目标表已经有数据。
我需要将 2 个表中的数据合并到第三个表中(都具有相同的模式)并生成旧标识值到新标识值的映射。显而易见的方法是使用游标遍历源表,沿途插入新旧标识值。有没有更好的(可能是面向集合的)方法来做到这一点?
更新:另外一点信息:目标表已经有数据。
Create your mapping table with an IDENTITY column for the new ID. Insert from your source tables into this table, creating your mapping.
SET IDENTITY_INSERT ON
for your target table.
Insert into the target table from your source tables joined to the mapping table, then SET IDENTITY_INSERT OFF
.
OUTPUT
我根据语句的子句创建了一个映射表MERGE
。不需要IDENTITY_INSERT
。
在下面的示例中,有RecordImportQueue
和RecordDataImportQueue
,并且RecordDataImportQueue.RecordID
是 的外键RecordImportQueue.RecordID
。这些暂存表中的数据需要转到Record
and RecordData
,并且必须保留 FK。
RecordImportQueue 到 Record 是使用一条MERGE
语句完成的,从它的 中生成一个映射表OUTPUT
,并且 RecordDataImportQueueRecordData
使用INSERT
来自连接到映射表的源表的 SELECT 。
DECLARE @MappingTable table ([NewRecordID] [bigint],[OldRecordID] [bigint])
MERGE [dbo].[Record] AS target
USING (SELECT [InstanceID]
,RecordID AS RecordID_Original
,[Status]
FROM [RecordImportQueue]
) AS source
ON (target.RecordID = NULL) -- can never match as RecordID is IDENTITY NOT NULL.
WHEN NOT MATCHED THEN
INSERT ([InstanceID],[Status])
VALUES (source.[InstanceID],source.[Status])
OUTPUT inserted.RecordID, source.RecordID_Original INTO @MappingTable;
之后,您可以将记录插入到引用表中,如下所示:
INSERT INTO [dbo].[RecordData]
([InstanceID]
,[RecordID]
,[Status])
SELECT [InstanceID]
,mt.NewRecordID -- the new RecordID from the mappingtable
,[Status]
FROM [dbo].[RecordDataImportQueue] AS rdiq
JOIN @MappingTable AS mt
ON rdiq.RecordID = mt.OldRecordID
虽然在原帖很久之后,我希望这可以帮助其他人,我很好奇任何反馈。
我想我会暂时在新表中添加一个额外的列来保存旧 ID。插入完成后,您可以将映射提取到另一个表中并删除该列。