您的位置:首页 > 其它

树形结构的处理--得到指定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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: