现在数据库中有这样的一张表:
编号 上级编号 级别 路径
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',0insert into t1 select 2,'b',0insert into t1 select 3,'c',1insert into t1 select 4,'d',1insert into t1 select 5,'e',2insert into t1 select 6,'f',2insert into t1 select 7,'g',3insert into t1 select 8,'h',3go--创建用户定义函数create function f_getNum(@id int)returns varchar(40)asbegin declare @ret varchar(4000),@pid int set @ret = right('00'+rtrim(@id),2) while exists(select 1 from t1 where [email protected] and parentid!=0) begin select @pid=parentid from t1 where [email protected] and parentid!=0 set @id = @pid set @ret = right('00'+rtrim(@id),2)[email protected] end return @retendgo--执行查询select a.id,name,dbo.f_getNum(a.id) as pathfrom t1 aorder by dbo.f_getNum(a.id) go--输出结果:/*id name path ----------- ---- ---------------------------------------- 1 a 013 c 01037 g 0103078 h 0103084 d 01042 b 025 e 02056 f 0206*/--删除测试数据drop function f_getNumdrop table t1
------解决方案--------------------
- SQL code
create table dd(编号 varchar(10),上级编号 varchar(10),级别 int,路径 varchar(50))insert into dd (编号 , 上级编号 , 级别)select '01',' ',0insert into dd (编号 , 上级编号 , 级别)select '02','01',1insert into dd (编号 , 上级编号 , 级别)select '03','02',2create function wsp(@编号 varchar(10))returns varchar(50)asbegin declare @路径 varchar(50),@上级编号 varchar(50) set @[email protected] while exists(select * from dd where [email protected] and 级别!=0) begin select @上级编号=上级编号 from dd where [email protected] set @[email protected] set @路径 = @[email protected] end return @路径endselect dbo.wsp('03')
------解决方案--------------------
都是层层查,没有好办法