How to calculate distance between two points in sql server

0

I would like to obtain the distance between two points in sql server, the problem I had previously, is that I had the data latitude and longitude in a single column, which I already managed to solve that problem through a split, now I would like to know how I can use the result to be able to calculate the distance between two points.

    SELECT TOP 10 [LDPID],[LatLon], SUBSTRING(LatLon, 1,9) AS LATITUD, SUBSTRING(LatLon, 11,19) AS LONGITUD FROM LDP

This is my result of the split

Now I would like to calculate the distance between the two points, I have been guided by this article but I can not find a way to use the results to calculate the distance. link

    
asked by Daniel 14.04.2018 в 21:52
source

2 answers

1

In order to correctly calculate the distance between two points in sql server and have a minimum margin of error, the following is done.

  --split para dos registros con la misma cantidad de numero
SELECT TOP 10 [LDPID], [LockID] ,[LockNumber],[LatLon], SUBSTRING(LatLon, 1,8) AS LATITUD, SUBSTRING(LatLon, 10,19) AS LONGITUD FROM LDP 

     --agregamos nueva columa a la base de datos
   alter table LDP add geoloc GEOGRAPHY null
      -- actualizamos la columa  geoloc

update LDP SET [geoloc] = GEOGRAPHY::Point(SUBSTRING(LatLon, 1,8) , SUBSTRING(LatLon, 10,19) , 4326) where LDPID = 1419


--declaramos las variables
declare @LAT GEOGRAPHY;
declare @LONG GEOGRAPHY;

select @LAT = [geoloc] FROM LDP where LDPID = 1201
select @LONG = [geoloc] FROM LDP where LDPID = 1419


select @LAT.STDistance(@LONG) as [Distance in Meters],
    @LAT.STDistance(@LONG)/ 1000 as [Distance in KM]
    
answered by 15.04.2018 / 02:24
source
1

To obtain the distance between 2 points with a SQL query you can do the following:

    select SQRT(POWER(CONVERT(decimal(9,6), T2.LATITUD)-CONVERT(decimal(9,6), T1.LATITUD),2)+POWER(CONVERT(decimal(9,6), T2.LONGITUD)-CONVERT(decimal(9,6), T1.LONGITUD),2)) as distancia
from 
(SELECT [LDPID],[LatLon], SUBSTRING(LatLon, 1,9) AS LATITUD, SUBSTRING(LatLon, 11,19) AS LONGITUD 
FROM LDP) as T1, 
(SELECT [LDPID],[LatLon], SUBSTRING(LatLon, 1,9) AS LATITUD, SUBSTRING(LatLon, 11,19) AS LONGITUD 
FROM LDP) as T2
where T1.LDPID=3 and T2.LDPID=1201

This query will find the distance between points 3 and 1201. In the first line the mathematical formula is used to find the distance between 2 points. Tell me if it works for you.

    
answered by 14.04.2018 в 22:30