--创建表
declare @T table (ID int,pid int,NAME varchar(6))
insert into @T
select 1,0,'上衣' union all
select 2,0,'鞋子' union all
select 3,0,'裤子' union all
select 4,1,'毛衣' union all
select 5,1,'衬衫' union all
select 6,2,'球鞋' union all
select 7,2,'皮鞋' union all
select 8,3,'西裤' union all
select 9,3,'筒裤' union all
select 10,4,'羊毛衣' union all
select 11,4,'牛毛衣' union all
select 12,5,'白衬衫' union all
select 13,5,'黑衬衫'
declare @i int
set @i =1 --参数假定为
;with
depts as(
select * from @T
where ID = 1
union all
select a.*
from @T a, depts b
where a.pid = b.ID
)
--取出所有id为1的子项
select * from depts
/*
ID pid NAME
----------- ----------- ------
1 0 上衣
4 1 毛衣
5 1 衬衫
12 5 白衬衫
13 5 黑衬衫
10 4 羊毛衣
11 4 牛毛衣
*/
@【叶子】http://blog.youkuaiyun.com/maco_wang 原创作品,转贴请注明作者和出处,留此信息。
本文介绍了一种使用SQL递归公用表表达式(CTE)的方法来查询具有层级结构的数据。通过创建一个临时表并填充有关服装分类的数据,演示了如何从根节点开始检索所有的子类别。
1319

被折叠的 条评论
为什么被折叠?



