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

困扰几天的树型结构查询问题
高人们
        你们好!我有一表,table1,表结构如下:

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


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

------解决方案--------------------

--我希望能用一条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
------解决方案--------------------
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))