views:

51

answers:

1

This is one of those questions where I'm having a hard time figuring out how to ask it so bare with me.

I have a stored procedure in SQL 2005 that calculates distance using the Haversine formula. Everything works quite nicely but I'd like to return the calculated distance with my result set. How do I go about adding that column/value pair?

 DECLARE @Longitude DECIMAL(18,8),
        @Latitude DECIMAL(18,8),
        @MinLongitude DECIMAL(18,8),
        @MaxLongitude DECIMAL(18,8),
        @MinLatitude DECIMAL(18,8),
        @MaxLatitude DECIMAL(18,8),
     @WithinMiles INT

Set @Latitude = -122.25336930
Set @Longitude = 37.50002600
Set @WithinMiles = 20

-- Calculate the Max Lat/Long
SELECT @MaxLongitude = dbo.LongitudePlusDistance(@Longitude, @Latitude, @WithinMiles),
       @MaxLatitude = dbo.LatitudePlusDistance(@Latitude, @WithinMiles)

-- Calculate the min lat/long
SELECT @MinLatitude = 2 * @Latitude - @MaxLatitude,
       @MinLongitude = 2 * @Longitude - @MaxLongitude

SELECT Top 10 *
FROM   Location
WHERE  LocationLongitude Between @MinLongitude And @MaxLongitude
       And LocationLatitude Between @MinLatitude And @MaxLatitude
       And dbo.CalculateDistance(@Longitude, @Latitude, LocationLongitude, LocationLatitude) <= @WithinMiles
ORDER BY dbo.CalculateDistance(@Longitude, @Latitude, LocationLongitude, LocationLatitude)

--Return the result of dbo.CalculateDistance

Any pointers? Including the correct way to ask this question?

(Oh, and yes, this is not the stored procedure since I was playing with the query directly that's what I pasted in here.)

+1  A: 

I think this is what your are asking for

    SELECT Top 10 *,dbo.CalculateDistance(@Longitude, @Latitude, LocationLongitude, LocationLatitude) as 'Calculated Distance'
FROM   Location
WHERE  LocationLongitude Between @MinLongitude And @MaxLongitude
       And LocationLatitude Between @MinLatitude And @MaxLatitude
       And dbo.CalculateDistance(@Longitude, @Latitude, LocationLongitude, LocationLatitude) <= @WithinMiles
ORDER BY dbo.CalculateDistance(@Longitude, @Latitude, LocationLongitude, LocationLatitude)
Gratzy
Brilliant! That's exactly what I was looking for. Is there a technical name for this?
Mikecancook
No not that I know of, you can add literals or variables to your select list all you want the 'Calculated Distance' string is called an allias
Gratzy