我有一张这样的表:
CREATE TABLE IF NOT EXISTS THING(
Id int NOT NULL IDENTITY(1, 1),
IdParent int,
randomtext varchar(255)
)
我想用他们的孩子,孙子们复制给定的id列表,但是当我尝试它时保留古代父ID,因此不保留层次结构 给出这样的东西:
| Id | IdParent | random text |
-------------------------------
| 1 | 0 | "aaaaaaaaa" |
| 2 | 1 | "tt" |
| 3 | 2 | "third" |
| 4 | 0 | "fourth" |
| 5 | 0 | "randOther" |
如果我给出id列表(1,4)和另一个像" 10"这样的parntid值,它会复制id为1和4的行,新的父ID为10,但重复的孩子会变成新的插入父母,以便保持层次结构
| Id | IdParent | random text |
-------------------------------------
| 1 | 0 | "aaaaaaaaa" |
| 2 | 1 | "tt" |
| 3 | 2 | "third" |
| 4 | 0 | "fourth" |
| 5 | 0 | "randOther" |
| 6 | 10 | "aaaaaaaaa -copy" |
| 7 | 6 | "tt- copy" |
| 8 | 7 | "third- copy" |
| 9 | 10 | "fourth- copy" |
我现在设法做的就是使用此查询将所有副本放入新父级,但我不想将所有孩子都放在新父级中
WITH HIERARCHY (Id)
AS (SELECT Id FROM THING
WHERE Id IN (1,4)
UNION ALL
SELECT e.Id
FROM THING e
INNER JOIN HIERARCHY h ON e.IdParent = h.Id
)
INSERT INTO THING (IdParent, randomtext)
SELECT 10, randomtext
FROM THING
WHERE Id IN (SELECT * FROM HIERARCHY)
(查询(应该在sql server 2008和oracle中运行)