子父级关系进行copy其他表,关系不变,Id变

--当前是为了解决具有层级关系,需要将该层级关系copy到其他表中,关系不发生变化,Id 需要进行变化
--将原始子父级 关系保留,父级Id 保留,主键Id 自动生成

SELECT NEWID() AS CategoryId,
       ParentCategoryId,
       CategoryId AS TempCategoryId,
       ParentCategoryId AS TempParentCategoryId
INTO #ProjectCategoryTemplate
FROM dbo.TPDM_ProjectCategoryTemplate;

--重点来了,此处为更新 具有父级的原始父级Id
--可以理解为A表为子表,B表为父表
--子表与父表进行关联后,去更新子表的父级也就是父表的主键Id 到子表的ParentCategoryId

UPDATE A
SET A.ParentCategoryId = B.CategoryId
FROM #ProjectCategoryTemplate A
    INNER JOIN #ProjectCategoryTemplate B
        ON B.TempCategoryId = A.TempParentCategoryId;

--此处可用可不用,该处是可以将对应集合挂靠在某个层级下

UPDATE #ProjectCategoryTemplate
SET ParentCategoryId = 1
SELECT *
FROM #ProjectCategoryTemplate
DROP TABLE #ProjectCategoryTemplate;

附一份完整的脚本段


SELECT NEWID() AS CategoryId,
       ParentCategoryId,
       CategoryId AS TempCategoryId,
       ParentCategoryId AS TempParentCategoryId
INTO #ProjectCategoryTemplate
FROM dbo.TPDM_ProjectCategoryTemplate;

UPDATE A
SET A.ParentCategoryId = B.CategoryId
FROM #ProjectCategoryTemplate A
    INNER JOIN #ProjectCategoryTemplate B
        ON B.TempCategoryId = A.TempParentCategoryId;


UPDATE #ProjectCategoryTemplate
SET ParentCategoryId = 1
SELECT *
FROM #ProjectCategoryTemplate
DROP TABLE #ProjectCategoryTemplate;

你可能感兴趣的:(sql,数据库)