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

多级目录问题!求助^^
现在数据库中有这样的一张表:
编号 上级编号 级别 路径
01 0 
02 01 1 
03 02 2
现在要做的就是使用SQL语句将这个路径求解出来,就比如编号01的路径就是01,编号03的路径就是010203,因为数据量比较大的,
所以能否用SQL语句求出来呢?或者有其他方法吗?谢谢大家,帮个忙^

------解决方案--------------------
参考

SQL code
--生成测试数据
create table t1(id int,name char(1),parentid int)
insert into t1 select 1,'a',0
insert into t1 select 2,'b',0
insert into t1 select 3,'c',1
insert into t1 select 4,'d',1
insert into t1 select 5,'e',2
insert into t1 select 6,'f',2
insert into t1 select 7,'g',3
insert into t1 select 8,'h',3
go

--创建用户定义函数
create function f_getNum(@id int)
returns varchar(40)
as
begin
    declare @ret varchar(4000),@pid int
    set @ret = right('00'+rtrim(@id),2)
    while exists(select 1 from t1 where id=@id and parentid!=0)
    begin
        select @pid=parentid from t1 where id=@id and parentid!=0
        set @id = @pid
        set @ret = right('00'+rtrim(@id),2)+@ret
    end
    return @ret
end
go


--执行查询
select 
    a.id,name,dbo.f_getNum(a.id) as path
from 
    t1 a
order by
    dbo.f_getNum(a.id) 
go

--输出结果:
/*
id          name path                                     
----------- ---- ---------------------------------------- 
1           a    01
3           c    0103
7           g    010307
8           h    010308
4           d    0104
2           b    02
5           e    0205
6           f    0206
*/

--删除测试数据
drop function f_getNum
drop table t1

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


create table dd(编号 varchar(10),上级编号 varchar(10),级别 int,路径 varchar(50))
insert into dd (编号  ,   上级编号   , 级别)select '01',' ',0
insert into dd (编号  ,   上级编号   , 级别)select '02','01',1
insert into dd (编号  ,   上级编号   , 级别)select '03','02',2




create function wsp(@编号  varchar(10))
returns varchar(50)
as
begin
       declare @路径 varchar(50),@上级编号  varchar(50)
    set @路径=@编号
        while exists(select * from dd where 编号=@编号 and 级别!=0)
        begin
              select @上级编号=上级编号 from dd where 编号=@编号
        set @编号=@上级编号
              set @路径 = @上级编号+@路径
      end
      return @路径
end

select dbo.wsp('03')

------解决方案--------------------
都是层层查,没有好办法