sql查询层级分类

先上个效果图吧

CTE递归查询里面用了一些小的技巧,查询出结果以后在前端用表格展示出来,层级视觉效果还是很明显的

with tree as
(
select [ID],[Name],[Address],[Remark],SortNo,Cast(RANK() OVER(order by SortNo,Name) as nvarchar(4000)) Code,cast('' as varchar) as prex from SmartHospital where ID=1
union all
select a.[ID],a.Name,a.[Address],a.[Remark],a.SortNo,b.Code +Cast(RANK() OVER(order by a.SortNo,a.Name) as nvarchar(4000)),cast(b.prex+' ' as varchar) from SmartHospital a,tree b where a.PID=b.ID
)
select ID,prex+Name as Name,Address,Remark,SortNo from tree order by Code

 

posted @ 2017-02-12 11:30  小破天  阅读(2087)  评论(0编辑  收藏  举报