with CTE as
(
-->Begin 一个定位点成员
select ID, PersonName,ParentID,cast(PersonName as nvarchar(max)) as TE,
ROW_NUMBER()over(order by getdate()) as OrderID
--最关键是上面这个字段,要获取排序字段,按字符串来排序。
--其中窗口函数必须要使用order by,但是不能用整型,那就用时间吧
from tmpTPStmp where ParentID=0
-->End
union all
-->Begin一个递归成员
select tmpTPStmp.ID, tmpTPStmp.PersonName,tmpTPStmp.ParentID,cast(replicate(' ',len(CTE.TE))+'|_'+tmpTPStmp.PersonName as nvarchar(MAX)) as TE,
CTE.OrderID*100+ROW_NUMBER()over(Order by GETDATE()) as OrderID
from tmpTPStmp inner join CTE
on tmpTPStmp.ParentID=CTE.ID
-->End
)
select * from CTE
order by LTRIM(OrderID)--最后将这个整型数据转换为字符串型的进行排序