CREATE FUNCTION [dbo].[udf_CalculateDistance]
(@Lat1 decimal(9,4), @Long1 decimal(9,4), @latitude decimal(9,4), @longitude decimal(9,4))
RETURNS decimal(9,4)
AS
BEGIN
DECLARE @Result decimal(9,4)
SET @Result = (3958.75 * ( Atan(Sqrt(1 - power(((Sin(@Lat1/57.2958) * Sin(@latitude/57.2958)) +
(Cos(@Lat1/57.2958) * Cos(@latitude/57.2958) * Cos((@longitude/57.2958) - (@Long1/57.2958)))), 2)) /
((Sin(@Lat1/57.2958) * Sin(@latitude/57.2958)) + (Cos(@Lat1/57.2958) * Cos(@latitude/57.2958) *
Cos((@longitude/57.2958) - (@Long1/57.2958))))))
Return @result
END
//then in your stored proc
SELECT @lat1= latitude,
@long1 = longitude
FROM ZipCodes
WHERE zipcodes = @ZipCode
SELECT
ZipCodes ,
dbo.udf_CalculateDistance(@lat1,@long1,a.latitude,a.longitude) as [DistanceInMiles]
FROM ZipCodes as a
WHERE a.DistanceInMiles <= @GivenMileRadius
--AND ZipCodes <> @ZipCode
ORDER BY DistanceInMiles
|