当前位置: 代码迷 >> Sql Server >> 求解答。该如何处理
  详细解决方案

求解答。该如何处理

热度:10   发布时间:2016-04-27 12:04:58.0
求解答。
各位老大。。想问下。。。

名称 名号 级别
国家 01 1
省 0101 2 
市 010101 3
地区 01010101 4

这样的数据有好多,怎么让他自动匹配成这样的数据?
例子------------------->结果
地区 国家>省>市>地区
省 国家>省
市 国家>省>市
用SQL能实现么?

------解决方案--------------------
给个案例 参考,套用一下下
SQL code
if object_id('[tb]') is not null drop table [tb]create table [tb] (id int,name varchar(1),pid int)insert into [tb]select 1,'A',0 union allselect 2,'B',1 union allselect 3,'D',1 union allselect 4,'C',2 union allselect 5,'D',2 union allselect 6,'A',4 union allselect 7,'E',5 union allselect 8,'F',5GO;with cteas(    select   *,[path]=cast([name]+'->' as varchar(100)) ,[level] = 1 from tb where pid = 0    union all    select a.*,  cast(c.[path]+a.[name]+'->' as varchar(100)),[level]+1 from cte c ,tb a where a.pid = c.id)select * from cte
  相关解决方案