您的位置:程序门 -> ms-sql server -> 疑难问题



困扰几天的树型结构查询问题


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


困扰几天的树型结构查询问题[已结贴,结贴人:dwtxkj888]
发表于:2007-05-12 08:12:24 楼主
高人们
        你们好!我有一表,table1,表结构如下:

    子级                           父级
    东莞市                       广东
    深圳市                       广东
    珠海市                       广东
    长安镇                   东莞市
    虎门镇                   东莞市
    锦厦村                   长安镇
    厦边村                   长安镇
    成都市                   四川省
    绵羊市                   四川省
    金牛区                   成都市
    五候区                   成都市


我希望能用一条sql语句查询出父级为广东的下面所有城市及县镇村,请问应该如何实现,在线等待,多谢了,解决完后立即结帖.
发表于:2007-05-12 08:16:041楼 得分:0
补充,希望跟每一层做一标识!
发表于:2007-05-12 08:23:202楼 得分:20

--我希望能用一条sql语句查询出父级为广东的下面所有城市及县镇村,请问应该如何实现,在线等待,多谢了,解决完后立即结帖.

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_str(@pid   varchar(20))
returns   varchar(8000)
as
begin
declare   @re   varchar(8000),@str   varchar(20)
set   @re=@pid
select   @re=@re+ '-> '+id,@pid=id   from   table1   where   pid=@pid
while   @@rowcount> 0
select   @re=@re+ '-> '+id,@pid=id   from   table1   where   pid=@pid
return   @re
end
go
select   dbo.fn_str( '广东 ')

drop   table   table1
drop   function   dbo.fn_str
发表于:2007-05-12 08:33:133楼 得分:80
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( '广东 ')

drop   table   table1
drop   function   dbo.fn_table
发表于:2007-05-12 08:33:444楼 得分:0
不好意思,偷了2楼好多代码
发表于:2007-05-12 09:06:305楼 得分:0
感谢了,真正感受到这里高人真是多啊


快速检索

最新资讯
热门点击