求一个好办法!

ygghost 2004-04-19 03:45:41
我的程序里有个树型的数据结构如下:
==================================
id pid name
1 0 一级分类
2 0 一级分类
3 1 二级分类
4 1 二级分类
5 1 二级分类
6 2 二级分类
7 2 二级分类
8 2 二级分类
9 8 三级分类
10 8 三级分类
=======================================
我通过一个id值把他的父路径都给列出来!
如果苯方法,
1 就是id=9,找到他的pid=8
2 根据pid=8判断他上一个结点id是8;id=8的时候pid=2;
3 根据pid=2判断他上一个结点id是2;这时的pid=0;就说明到跟结点了。
====
请问是不是可以通过一些简洁的方法来操作呢?比如建立一个视图,存储过程之类的,请高手指点一下。
是不是我数据结构设计不好呢?
...全文
25 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2004-04-19
  • 打赏
  • 举报
回复
--测试

--测试数据
create table tb(id int,pid int,name varchar(10))
insert tb select 1, 0,'一级分类'
union all select 2, 0,'一级分类'
union all select 3, 1,'二级分类'
union all select 4, 1,'二级分类'
union all select 5, 1,'二级分类'
union all select 6, 2,'二级分类'
union all select 7, 2,'二级分类'
union all select 8, 2,'二级分类'
union all select 9, 8,'三级分类'
union all select 10,8,'三级分类'
go

--创建处理函数
create function f_getparentid(@id int)
returns @re table(id int)
as
begin
declare @pid int
select @pid=pid from tb where id=@id
while @pid<>0
begin
insert into @re values(@pid)
select @pid=pid from tb where id=@pid
end
return
end
go

--调用实现查询
select a.* from tb a join f_getparentid(10) b on a.id=b.id
go

--删除测试
drop table tb
drop function f_getparentid

/*--测试结果

id pid name
----------- ----------- ----------
2 0 一级分类
8 2 二级分类

(所影响的行数为 2 行)
--*/
zjcxc 2004-04-19
  • 打赏
  • 举报
回复
create function f_getparentid(@id int)
returns @re table(id int)
as
begin
declare @pid int
select @pid=pid from tb where id=@id
while @pid<>0
begin
insert into @re values(@pid)
select @pid=pid from tb where id=@pid
end
return
end
go

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧