日期:2014-05-18 浏览次数:20606 次
--测试数据 DECLARE @t TABLE(ID char(3),PID char(3),Name nvarchar(10)) INSERT @t SELECT '001',NULL ,'山东省' UNION ALL SELECT '002','001','烟台市' UNION ALL SELECT '004','002','招远市' UNION ALL SELECT '003','001','青岛市' UNION ALL SELECT '005',NULL ,'四会市' UNION ALL SELECT '006','005','清远市' UNION ALL SELECT '007','006','小分市' --深度排序显示处理 --生成每个节点的编码累计(相同当单编号法的编码) DECLARE @t_Level TABLE(ID char(3),Level int,Sort varchar(8000)) DECLARE @Level int SET @Level=0 INSERT @t_Level SELECT ID,@Level,ID FROM @t WHERE PID IS NULL WHILE @@ROWCOUNT>0 BEGIN SET @Level=@Level+1 INSERT @t_Level SELECT a.ID,@Level,b.Sort+a.ID FROM @t a,@t_Level b WHERE a.PID=b.ID AND b.Level=@Level-1 END --显示结果 SELECT SPACE(b.Level*2)+'|--'+a.Name FROM @t a,@t_Level b WHERE a.ID=b.ID ORDER BY b.Sort /*--结果 |--山东省 |--烟台市 |--招远市 |--青岛市 |--四会市 |--清远市 |--小分市 --*/
------解决方案--------------------
Declare @T Table ( id Int, pid Int, name varchar(20) ) Insert Into @T Select 1, 0, 'AAA' Union Select 2, 0, 'BBB' Union Select 3, 1, 'CCC' Union Select 4, 1, 'DDD' Union Select 5, 2, 'EEE' Union Select 6, 2, 'FFF' Union Select 7, 2, 'GGG' Select * From @T Order By case when Pid=0 then id else pid End,id