Quassnoi की एक क्वेरी के आधार पर इसे आज़माएं। का लेख Adjacency List vs Nested Sets :SQL सर्वर :
WITH q AS
(
SELECT h.*, 1 AS level
FROM Table1 h
WHERE id = 3
UNION ALL
SELECT hp.*, level + 1
FROM q
JOIN Table1 hp
ON hp.id = q.ParentGroupID
), q2 AS (
SELECT
ID,
ParentGroupID,
SomeValue,
(SELECT MAX(level) FROM q) - level AS level
FROM q
)
INSERT INTO table1
SELECT
(SELECT MAX(ID) FROM Table1) + level + 1 AS ID,
CASE WHEN level = 0 THEN -1
ELSE (SELECT MAX(ID) FROM Table1) + level
END AS ParentGroupID,
SomeValue + '-cloned'
FROM q2
आपके परीक्षण डेटा पर चलने पर परिणाम:
ID ParentGroupID SomeValue
1 -1 a
2 1 b
3 2 c
4 -1 a-cloned
5 4 b-cloned
6 5 c-cloned