Distance Stored Procedure

We will be calculated distances between points in lat/long and will need a function in SQL to help us with this. We will input lat1, lon1, lat2, lon2 and return a float with the distance between the points. This command will add the function to your database:

CREATE FUNCTION [dbo].[LatLonRadiusDistance]
(
@lat1Degrees float,
@lon1Degrees float,
@lat2Degrees float,
@lon2Degrees float
)
RETURNS float
AS
BEGIN

DECLARE @earthSphereRadiusNauticalMiles as float
DECLARE @nauticalMileConversionToMilesFactor as float
SELECT @earthSphereRadiusNauticalMiles = 6366.707019
SELECT @nauticalMileConversionToMilesFactor = .621371

-- convert degrees to radians
DECLARE @lat1Radians float
DECLARE @lon1Radians float
DECLARE @lat2Radians float
DECLARE @lon2Radians float
SELECT @lat1Radians = (@lat1Degrees / 180) * PI()
SELECT @lon1Radians = (@lon1Degrees / 180) * PI()
SELECT @lat2Radians = (@lat2Degrees / 180) * PI()
SELECT @lon2Radians = (@lon2Degrees / 180) * PI()

-- formula for distance from [lat1,lon1] to [lat2,lon2]
RETURN ROUND(2 * ASIN(SQRT(POWER(SIN((@lat1Radians - @lat2Radians) / 2) ,2)
+ COS(@lat1Radians) * COS(@lat2Radians) * POWER(SIN((@lon1Radians - @lon2Radians) / 2), 2)))
* (@earthSphereRadiusNauticalMiles * @nauticalMileConversionToMilesFactor), 4)

END