整数到 guid 主键数据库迁移

Integer to guid primary key database migration

我正在尝试从基于 int 的主键迁移到基于 guid 的系统,但我在迁移自引用时遇到了问题 table

Entity
---------
ID
ParentID
AnotherParentID

在查询 table 时,我正在为每一行创建新的 guid ID,但是如何为具有 ID 作为外键的行设置相同的 guid 值在 ParentIDAnotherParentID 字段上?

SELECT 
    newid() as ID,
    (SELECT e.ID ...?) as ParentID,
    (SELECT e.ID ...?) as AnotherParentID,
FROM Entity e

如果 paretnID 是外键:

Select NEWID(), ID, EP.ParentIDGUID, E.ParentID, EP2.AnotherParentID, EP2.AnotherParentIDGUID from dbo.Entity E  
        INNER JOIN 
        (Select MAX(NEWID()) as ParentIDGUID, ParentID FROM dbo.Entity GROUP BY ParentID) EP ON EP.ParentID = E.ParentID
        INNER JOIN 
        (Select MAX(NEWID()) as AnotherParentIDGUID, AnotherParentID FROM dbo.Entity GROUP BY AnotherParentID) EP2 ON EP2.AnotherParentID = E.AnotherParentID

或者如果它们是同一个外键 table:

Select NEWID() as guidID, ID
INTO #tp 
 from dbo.Entity E


Select EP.ID, EP.guidID, E.ParentID, EP2.guidID, E.AnotherParentID, EP3.guidID from dbo.Entity E  
    INNER JOIN 
    #tp EP ON EP.ID = E.ID
    INNER JOIN 
    #tp EP2 ON EP2.ID = E.ParentID
    INNER JOIN 
    #tp EP3 ON EP3.ID = E.AnotherParentID


DROP TABLE #tp 

@MRsa 的回答给出了多行,因为加入了 ParentIDAnotherParentID(因为多行可以具有相同的 ParentID/AnotherParentID)。

这是我目前有效的实现,我不确定是否有更好的方法来处理这个问题

CREATE TABLE #tmp (
    Id uniqueidentifier null,
    OldId integer null
)

INSERT INTO #tmp (Id, OldId)
SELECT NEWID(), Id FROM OldTable

INSERT INTO NewTable
SELECT
    (SELECT Id FROM #tmp WHERE OldId = i.Id) as ID,
    (SELECT Id FROM #tmp WHERE OldId = i.ParentId) as ParentID,
    (SELECT Id FROM #tmp WHERE OldId = i.AnotherParentID) as AnotherParentID,
FROM OldTable i