SQL SERVER 实现计算距离方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/roy_88/article/details/79744690

SQL2008以上的版本支持:

注意,在计算过程中要处理好数据,如:经纬度不能有NULL会报错,有0会计算不正确,这类最好过滤,在现实应用中可借用计算列简化语句

e.g.
use Tempdb
go
--> --> 中国风(Roy)生成測試數據
 
if not object_id(N'Tempdb..#Destn') is null
	drop table #Destn
Go
Create table #Destn([Name] nvarchar(50),[Latitude] FLOAT,[Longitude] FLOAT)
Insert #Destn
select N'广州',23.1292,113.264 union all
select N'深圳',22.5431,114.058 union all
select N'东莞',23.0205,113.752 union all
select N'佛山',23.0215,113.121 union all
select N'河源',23.7435,114.7 union all
select N'惠州',23.1118,114.416 UNION ALL
select N'珠海',22.2707,113.577
GO
--计算距离珠海的距离
--取珠海坐标可用以下两种方法,使用Point和STGeomFromText时注意(Longitude、Latitude)位置是相反的
DECLARE @geog1 GEOGRAPHY,@geog2 GEOGRAPHY
Select @geog1=geography::Point([Latitude], [Longitude], 4326)
,@geog2=geography::STGeomFromText('POINT('+RTRIM(CAST([Longitude] AS DECIMAL(18,10)))+' '+RTRIM(CAST([Latitude] AS DECIMAL(18,10)))+')', 4326)
 from #Destn WHERE [Name]=N'珠海'
--米换算公里,需除以1000
SELECT *,
       geography::Point([Latitude], [Longitude], 4326).STDistance(@geog1) / 1000 AS [Distance(km)-Point],
	   geography::Point([Latitude], [Longitude], 4326).STDistance(@geog2) / 1000 AS [Distance(km)-STGeomFromText]
FROM #Destn
ORDER BY 4;

/*
Name	Latitude	Longitude	Distance(km)-Point	Distance(km)-STGeomFromText
珠海	22.2707	113.577	0	0
深圳	22.5431	114.058	57.9889965363554	57.9889965363554
东莞	23.0205	113.752	84.9582310757556	84.9582310757556
佛山	23.0215	113.121	95.444281324033	95.444281324033
广州	23.1292	113.264	100.362215426049	100.362215426049
惠州	23.1118	114.416	126.916238881864	126.916238881864
河源	23.7435	114.7	199.639422259809	199.639422259809  
*/


猜你喜欢

转载自blog.csdn.net/roy_88/article/details/79744690