1CREATE FUNCTION dbo.DistanceFunc
2(
3 @Latitude1 decimal(11,6),
4 @Longitude1 decimal(11,6),
5 @Latitude2 decimal(11,6),
6 @Longitude2 decimal(11,6)
7)
8
9RETURNS decimal(11, 6) --returns distance in miles
10
11AS
12
13BEGIN
14 --If the 2 locations are the same, return 0 miles
15 IF @Latitude1 = @Latitude2 AND @Longitude1 = @Longitude2
16 RETURN 0
17
18 --Convert the points from degrees to radians
19 SET @Latitude1 = @Latitude1 * PI() / 180
20 SET @Longitude1 = @Longitude1 * PI() / 180
21 SET @Latitude2 = @Latitude2 * PI() / 180
22 SET @Longitude2 = @Longitude2* PI() / 180
23
24 --Temp var
25 DECLARE @Distance decimal(18,13)
26 SET @Distance = 0.0
27
28 --Compute the distance
29 SET @Distance = SIN(@Latitude1) * SIN(@Latitude2) + COS(@Latitude1) *
30 COS(@Latitude2) * COS(@Longitude2 - @Longitude1)
31
32 --Are the latitude and longitude points the same? Return 0
33 IF @distance = 1
34 RETURN 0
35
36 --Convert to miles (3963 = earth's radius)
37 RETURN 3963 * (-1 * ATAN(@Distance / SQRT(1 - @Distance * @Distance)) + PI() / 2)
38END
39