| 发表于: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 | | |
|