简体   繁体   English

Integer 指导主键数据库迁移

[英]Integer to guid primary key database migration

I'm trying to migrate from int based primary keys to guid based system, and I'm having trouble with migrating self referenced table我正在尝试从基于 int 的主键迁移到基于 guid 的系统,但在迁移自引用表时遇到了问题

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

When querying the table I'm creating new guid ID for each row, but how can I set that same guid value for rows that have that ID as foreign key on ParentID or AnotherParentID fields?查询表时,我正在为每一行创建新的 guid ID ,但是如何为具有该ID作为ParentIDAnotherParentID字段上的外键的行设置相同的 guid 值?

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

IF paretnIDs are Foreign keys:如果 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

or if they are foreign key on same 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 answer gives multiple rows because of joining on ParentID or AnotherParentID (since multiple rows can have same ParentID/AnotherParentID). @MRsa 答案给出了多行,因为加入了ParentIDAnotherParentID (因为多行可以具有相同的 ParentID/AnotherParentID)。

This is my current implementation that works, I'm not sure if there is any better way to handle this这是我当前有效的实现,我不确定是否有更好的方法来处理这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM