34,576
社区成员
发帖
与我相关
我的任务
分享
use test
go
if object_id('test.dbo.tb') is not null drop table tb
-- 创建数据表
create table tb
(
ID int,
NAME varchar(max),
PID int
)
go
--插入测试数据
insert into tb select 1,'北京',0
union all select 2,'海淀',1
union all select 3,'朝阳',1
union all select 4,'上海',0
union all select 5,'浦东',4
union all select 6,'广东',0
union all select 7,'广州',6
union all select 8,'天河',7
union all select 9,'海珠',7
union all select 10,'白云',7
go
--代码实现
;with t as(
select * from tb where PID=0
union all
select a.ID,NAME=b.NAME+'/'+a.NAME,a.PID from tb a,t b where a.PID=b.ID
)
select * from t order by ID
/*测试结果
ID NAME PID
----------------------------------
1 北京 0
2 北京/海淀 1
3 北京/朝阳 1
4 上海 0
5 上海/浦东 4
6 广东 0
7 广东/广州 6
8 广东/广州/天河 7
9 广东/广州/海珠 7
10 广东/广州/白云 7
(10 行受影响)
*/