WITH tree
AS
(
SELECT dwpid, dwid,1 AS x2level,dwmc,
/*CAST(dwmc AS NVARCHAR(max)) x2name,*/
CAST(+dwid AS NVARCHAR(max)) x2id
FROM cf_xzdw
WHERE dwpid ='0'
UNION ALL
SELECT c.dwpid, c.dwid, tree.x2level + 1,c.dwmc,
/*CAST(REPLICATE('-', x2level * 4) + c.dwmc AS NVARCHAR(max)) x2name,*/
tree.x2id +'-'+ CAST(c.dwid AS NVARCHAR(max)) x2id
FROM cf_xzdw c
INNER JOIN tree
ON c.dwpid = tree.dwid
)
SELECT dwmc, dwid, dwpid FROM tree
ORDER BY x2id;
参考:
http://blog.chinaunix.net/uid-451-id-3344447.html