if object_id('t')is not null
drop table t
if object_id('f')is not null
drop function f
go
create table t (id varchar(2) ,mun varchar(2),name varchar(5))
insert into t select '1','1','clsa'
union all select '2','1','clsb'
union all select '3','1','clsc'
union all select '4','2','clsd'
go
create function f (@id varchar(2))
returns @t table(id varchar(2),level int)
as
begin
declare @level int
set @level=1
insert into @t select @id,@level
while @@rowcount>0
begin
set @level=@level + 1
insert into @t select a.id,@level
from t a ,@t b
where a.mun=b.id
and b.level=@level-1
end
return
end
go
select a.* from t a ,dbo.f('1') b
where a.id=b.id