[英]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.