SQL Server使用geography数据类型对空间坐标周边搜索进行优化

首先,现有系统上有现成的坐标存储(节选)

Id          Name                             Longitude                               Latitude
----------- -------------------------------- --------------------------------------- ---------------------------------------
1           梧州南站                             111.215417                              23.397750
2           龙腾金院                             111.216583                              23.400806
3           中团变电站                            111.224861                              23.404806
4           龙圩大转盘西                           111.234417                              23.406611
5           龙圩大转盘北                           111.236500                              23.407444
6           龙城龙兴路口                           111.237917                              23.413500
7           龙城银兴路口                           111.240389                              23.416861
8           政贤路广场                            111.242611                              23.418167
9           苍梧大道东                            111.247167                              23.418611
10          恩义小学                             111.257139                              23.428861

现在需要查找给定坐标最近的站点

这里采用SQL2008以上版本提供的geography解法

1、在表中添加一个geography类型的列,名为 [GeoLocation]

ALTER TABLE [dbo].T_L_Station
ADD [GeoLocation] GEOGRAPHY
GO

2、把 [Latitude] 和 [Longitude] 的数字类型保存的经纬度坐标点,转换并更新到 [GeoLocation] 列中

UPDATE [dbo].T_L_Station
SET [GeoLocation] = geography::Point([Latitude], [Longitude], 4326)
GO

3、Select * 一下,便可以睇到数据库中存储的空间结果

4、采用 geography 类型内置的 STDistance 函数便可以求出,与已知坐标的距离了,在where order by一下就可以得到想要的结果喇,参考代码

SELECT  [Id]
      ,[Name]
      ,[ByStartDistance]
      ,[Longitude]
      ,[Latitude]
      ,[GeoLocation]
	  ,[GeoLocation].STDistance(geography::Point(23.47303, 111.32033, 4326)) as 距离
  FROM [dbo].[T_L_Station]
  --where [GeoLocation].STDistance(geography::Point(23.47303, 111.32033, 4326))<=200
  order by 距离

PS:23.47303, 111.32033 为已知坐标的经纬度。

这样是不是很简单:)