sql写法,子节点名称拼接上级节点名称

with T(id,[name],pid) as
(select 1,N'中国',-1 union all
select 2,N'山东',1 union all
select 3,N'济南',2 union all
select 4,N'青岛',2 union all
select 5,N'历下区',3 union all
select 6,N'崂山区',4 union all
select 7,N'河北',1 union all
select 8,N'石家庄',7),
cte as
(select id,convert(varchar,name) as name,pid,[name] as nam from T where pid=-1
       union all
  select t.id,convert(varchar,a.name+'-'+t.name),t.pid,t.name  from cte a,t where a.id=t.pid)
  
 select * from cte where nam='济南'

原文地址:https://www.cnblogs.com/zhangchengye/p/11081303.html