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

使用树形结构的查询。
表结构
id name Pid
1 通信 0
2 通信_1 1 
3 通信_2 1
4 通信_3 1
5 汽车 0 
6 汽车_1 5
7 移动 0
8 移动_1 7

一组树形结构,现在我传入了一组id,无序的,如何找出这个id是否为父节点,并且把这一组id中所有的子节点id显示?

比如,传入 2,1,4,7,8
显示
通信,通信_1,通信_3,移动,移动_1

------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
create table [test]([id] int,[name] varchar(6),[Pid] int)
insert [test]
select 1,'通信',0 union all
select 2,'通信_1',1 union all
select 3,'通信_2',1 union all
select 4,'通信_3',1 union all
select 5,'汽车',0 union all
select 6,'汽车_1',5 union all
select 7,'移动',0 union all
select 8,'移动_1',7

declare @str varchar(100)
set @str=''
select @str=@str+','+[name] from test
where id in(1,2,4,7,8)
select right(@str,len(@str)-1) as value
/*
value
---------------------------------------
通信,通信_1,通信_3,移动,移动_1
*/