sql树型查询

WITH a
AS  
(  
SELECT *,
FOrderPath=CAST(RIGHT(1000+FOrder,3) AS NVARCHAR(200)),
FPath=CAST(Id AS NVARCHAR(200)),
FLevel=0
 FROM Base_Class AS a WHERE  NOT EXISTS(SELECT 1 FROM Base_Class WHERE ID=a.PID)  
UNION ALL  
SELECT b.*,
CAST(a.FOrderPath + RIGHT(1000+b.FOrder,3)AS NVARCHAR(200)),
CAST((a.FPath + , + CAST(b.Id AS NVARCHAR(10)))AS NVARCHAR(200)),
FLevel=FLevel+1
 FROM a INNER JOIN Base_Class AS b ON b.PID=a.ID
)
SELECT * FROM a ORDER BY FOrderPath

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。