title: SQL 2003 Distance Latitude Longitude
body: <p>I have a table full of Dealers along with their latitude and longitude.  I am trying to determine the top n closest dealers to any given lat and lon.  I already have the function to calculate distance between locations, but I want to do as few calculations as possible (my table can contain many thousands of entries).  Currently I have to calculate the distance for each entry then sort them.  Is there any way to sort before I do the calculation to improve performance?</p>
  
  <p><a href="https://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula">This</a> question is good, but <strong>I will not always know my range.  Should I just pick an arbitrarily high range then refine my results?</strong>  I am thankful for any help the community can offer.</p>
  
  <pre><code>declare @Lat real
  declare @lon real
  
  Set @lat = 41.05
  Set @lon = -73.53 
  
  SELECT top 10
      MemberID,
      Address1,
      City,
      State,
      Zip,
      Phone,
      Lat,
      Lon,
      (SELECT fun_DistanceLatLon] (@Lat,@lon,Lat,Lon)) as mDistance --Calculate distance
  FROM
      Dealers
  Order by
      (SELECT fun_DistanceLatLon] (@Lat,@lon,Lat,Lon))
  </code></pre>