日期:2014-05-18  浏览次数:20419 次

求解答。
各位老大。。想问下。。。

名称 名号 级别
国家 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 all
select 2,'B',1 union all
select 3,'D',1 union all
select 4,'C',2 union all
select 5,'D',2 union all
select 6,'A',4 union all
select 7,'E',5 union all
select 8,'F',5
GO
;with cte
as
(
    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