Reputation: 3
I'm working with billions of rows of data, and each row has an associated start latitude/longitude, and end latitude/longitude. I need to calculate the distance between each start/end point - but it is taking an extremely long time. I really need to make what I'm doing more efficient.
Currently I use a function (below) to calculate the hypotenuse between points. Is there some way to make this more efficient? I should say that I have already tried casting the lat/longs as spatial geographies and using SQL built in STDistance() functions (not indexed), but this was even slower.
Any help would be much appreciated. I'm hoping there is some way to speed up the function, even if it degrades accuracy a little (nearest 100m is probably ok). Thanks in advance!
DECLARE @l_distance_m float
, @l_long_start FLOAT
, @l_long_end FLOAT
, @l_lat_start FLOAT
, @l_lat_end FLOAT
, @l_x_diff FLOAT
, @l_y_diff FLOAT
SET @l_lat_start = @lat_start
SET @l_long_start = @long_start
SET @l_lat_end = @lat_end
SET @l_long_end = @long_end
-- NOTE 2 x PI() x (radius of earth) / 360 = 111
SET @l_y_diff = 111 * (@l_lat_end - @l_lat_start)
SET @l_x_diff = 111 * (@l_long_end - @l_long_start) * COS(RADIANS((@l_lat_end + @l_lat_start) / 2))
SET @l_distance_m = 1000 * SQRT(@l_x_diff * @l_x_diff + @l_y_diff * @l_y_diff)
RETURN @l_distance_m
Upvotes: 0
Views: 296
Reputation: 7836
I haven't done any SQL programming since around 1994, however I'd make the following observations:
Upvotes: 2