[英]Integer to guid primary key database migration
我正在尝试从基于 int 的主键迁移到基于 guid 的系统,但在迁移自引用表时遇到了问题
Entity
---------
ID
ParentID
AnotherParentID
查询表时,我正在为每一行创建新的 guid ID
,但是如何为具有该ID
作为ParentID
或AnotherParentID
字段上的外键的行设置相同的 guid 值?
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
或者如果它们是同一张表上的外键:
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 答案给出了多行,因为加入了ParentID
或AnotherParentID
(因为多行可以具有相同的 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.