Search code examples
sql-server-2005haversine

How to Return Additional Columns With Values Generated in Stored Procedures On the 'Fly'?


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.)


Solution

  • 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)