Declare @subCount int Declare @Level while @subCount >0 begin insertinto #temp(ID,Level) Select ID,@Level+1from Catalog where ParentID in ( select ID from #tempwhereLevel= @Level ) set @Level = @Level+1 Select @subCount =Count(*) from Catalog where ParentID in ( select ID from #tempwhereLevel= @Level ) end