树形结构的处理--得到指定id的子id列表
2009-01-08 10:56
169 查看
--数据结构
表名tb,如果修改表名,则相应修改所有数据处理中涉及到的表名tb
id为编号(标识字段+主键)
pid为上级编号
name为名称,后面可以自行增加其他字段.
/*-- 得到指定id的子id列表 --*/
--不包含排序字段的情况
create function f_getchildid(@id int)
returns @re table(id int)
as
begin
insert into @re select id from tb where pid=@id
while @@rowcount>0
insert into @re select a.id
from tb a inner join @re b on a.pid=b.id
where a.id not in(select id from @re)
return
end
go
--包含排序字段的情况
create function f_getchildidsort(@id int)
returns @re table(id int,sortid varchar(8000))
as
begin
--为了数字排序正常,需要统一编码宽度
declare @idlen int,@idheader varchar(20)
select @idlen=max(len(id))
,@idheader=space(@idlen)
from tb
insert into @re select id,right(@idheader+cast(id as varchar),@idlen)
from tb where pid=@id
while @@rowcount>0
insert into @re select a.id,right(@idheader+cast(a.id as varchar),@idlen)+','+b.sortid
from tb a inner join @re b on a.pid=b.id
where a.id not in(select id from @re)
return
end
go
--调用示例,显示1的所有子.
select a.* from tb a inner join dbo.f_getchildidsort(1) b on a.id=b.id order by b.sortid
表名tb,如果修改表名,则相应修改所有数据处理中涉及到的表名tb
id为编号(标识字段+主键)
pid为上级编号
name为名称,后面可以自行增加其他字段.
/*-- 得到指定id的子id列表 --*/
--不包含排序字段的情况
create function f_getchildid(@id int)
returns @re table(id int)
as
begin
insert into @re select id from tb where pid=@id
while @@rowcount>0
insert into @re select a.id
from tb a inner join @re b on a.pid=b.id
where a.id not in(select id from @re)
return
end
go
--包含排序字段的情况
create function f_getchildidsort(@id int)
returns @re table(id int,sortid varchar(8000))
as
begin
--为了数字排序正常,需要统一编码宽度
declare @idlen int,@idheader varchar(20)
select @idlen=max(len(id))
,@idheader=space(@idlen)
from tb
insert into @re select id,right(@idheader+cast(id as varchar),@idlen)
from tb where pid=@id
while @@rowcount>0
insert into @re select a.id,right(@idheader+cast(a.id as varchar),@idlen)+','+b.sortid
from tb a inner join @re b on a.pid=b.id
where a.id not in(select id from @re)
return
end
go
--调用示例,显示1的所有子.
select a.* from tb a inner join dbo.f_getchildidsort(1) b on a.id=b.id order by b.sortid
相关文章推荐
- 树形结构的处理--得到指定id的父id列表
- MySql如何根据输入的id获得树形结构的子节点列表:使用自连+SUBSTRING_INDEX函数
- magento 得到树形结构的分类列表
- 追求完美很容易在开发上过度设计 -- 树形结构的设计不仅带来了代码开发量更可怕的是处理相应的复杂逻辑
- JSON复杂数据处理之Json树形结构数据转Java对象并存储到数据库的实现
- 树形结构数据后台处理:一次循环生成树
- ecshop调用指定ID分类下的文章列表(指定分类下的文章)
- 得到能打开指定类型文件的应用程序列表
- Magento admin Grid columns 取到的值二次处理,譬如取到的category_id 得到名字
- 树形结构的处理——组合模式(三)
- 得到指定字符串列表中,指定个数的字符串
- MVC3+EF4.1学习系列(十)----MVC+EF处理树形结构
- 得到指定字符串列表中,指定个数的字符串
- Java代码获取菜单列表的树形结构
- 遍历一个指定的目录(包含子目录和文件),用Jdom把该目录的树形结构写入xml文件中
- 关于多层级树形结构的项目列表
- 在树结构的表内得到指定父辈或子孙相关信息
- C#递归算法-遍历XML文件,以UL列表显示树形结构目录
- 在同一个下拉列表显示树形结构
- Java基础之IO流,使用File类以树形结构打印指定文件目录