,/*从根节点往下递归*/
x2 ( id, mid, pid, rid, way )
AS ( SELECT t1.id ,
t1.mid ,
t1.pid ,
CONVERT(VARCHAR(10), t1.pid) AS rid ,
CONVERT(VARCHAR(20), t1.pid + ',' + t1.mid) AS way
FROM x1 t1
WHERE t1.root_flag IS NULL
UNION ALL
SELECT t1.id ,
t1.mid ,
t1.pid ,
CONVERT(VARCHAR(10), LEFT(t2.way,
CHARINDEX(',', t2.way) - 1)) AS rid ,
CONVERT(VARCHAR(20), t2.way + ',' + t1.mid) AS way
FROM x1 t1
INNER JOIN x2 t2 ON t2.mid = t1.pid
)
SELECT id ,
mid ,
pid ,
rid
FROM x2
ORDER BY id