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

100分求教树型结构分层问题,急
create   table   table1(id   varchar(20),pid   varchar(20))
insert   table1
select   '东莞市 ', '广东 '
union   all   select   '深圳市 ', '广东 '
union   all   select   '珠海市 ', '广东 '
union   all   select   '长安镇 ', '东莞市 '
union   all   select   '虎门镇 ', '东莞市 '
union   all   select   '锦厦村 ', '长安镇 '
union   all   select   '厦边村 ', '长安镇 '
union   all   select   '成都市 ', '四川省 '
union   all   select   '绵羊市 ', '四川省 '
union   all   select   '金牛区 ', '成都市 '
union   all   select   '五候区 ', '成都市 '


GO
CREATE   function   fn_table(@pid   varchar(20))
returns   @r   table   (
id   varchar(20),pid   varchar(20),lev   int
)
as
begin
        declare   @lev   int
        set   @lev=1
        insert   @r   select   id,pid,@lev   from   table1   where   pid=@pid
        while   exists   (select   id,pid,@lev+1   from   table1   where   pid   in   (select   id   from   @r   where   lev=@lev))
        begin
              insert   @r   select   id,pid,@lev+1   from   table1   where   pid   in   (select   id   from   @r   where   lev=@lev)
              set   @lev=@lev+1
        end
        return  
end
go

select   *   from   dbo.fn_table( '广东 ')


问题的提升,希望能将查询结果一层一层地分层显示出来,其显示结果希望如下
  广东
        --东莞市
                --长安镇
                        --锦厦村
                        --厦边村
                --虎门镇
                        --北栅村
                        --南栅村
        --深圳市
        --珠海市
四川省
        --成都市
            --金牛区
            --武候区
        --绵阳市


请问高手如果是这样显示应该如何操作呢???     100分,搞定后立即结贴.谢谢了


------解决方案--------------------
http://community.csdn.net/Expert/topic/5331/5331207.xml?temp=.5283472
和你的差不多,参考下
------解决方案--------------------
看邹建的方法

--测试数据
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 ', '青岛市 '
U