SQL Server 利用 geography 計算地理位置距離、距我最近排序

SQL Server 有個字段類型爲 geography,這個類型存經緯度,就能夠利用經緯度排序了。sql

(注意,還有一個近似類型:geometry,這個是用來計算二維平面的,不適合經緯度).net

如何往 geography 存儲值?blog

insert into citys(cityName, geo) values('北京', geography::STPointFromText('POINT (116.555963 39.711394)', 4326));
insert into citys(cityName, geo) values('上海', geography::STPointFromText('POINT (121.560028 31.175737)', 4326));
insert into citys(cityName, geo) values('廣州', geography::STPointFromText('POINT (113.465217 23.087146)', 4326));
insert into citys(cityName, geo) values('深圳', geography::STPointFromText('POINT (114.090725 22.507165)', 4326));
insert into citys(cityName, geo) values('成都', geography::STPointFromText('POINT (104.137788 30.524926)', 4326));
insert into citys(cityName, geo) values('杭州', geography::STPointFromText('POINT (120.382601 30.157892)', 4326));
insert into citys(cityName, geo) values('重慶', geography::STPointFromText('POINT (106.603025 29.532371)', 4326));
insert into citys(cityName, geo) values('武漢', geography::STPointFromText('POINT (114.403479 30.556776)', 4326));排序

利用的是 geography::STPointFromText()。索引

第一個參數 POINT() 裏面再跟經度、緯度。ci

第二個參數 4326 表明 GCS-WGS-1984 座標系。具體本文後面會列出相關連接。get

如何查詢?it

declare @currentLocation geography
select @currentLocation = geography::STPointFromText('POINT (114.403479 30.556776)', 4326)
select *, geo.STDistance(@currentLocation) as 距離 from citys
    where geo.STDistance(@currentLocation) < 1000000
    order by geo.STDistance(@currentLocation)io

這個 SQL 語句利用 geo.STDistance(@currentLocation)  < 1000000 限定了 1000 千米之內的數據,而後按由近到遠排序。百度

關鍵詞總結

  • geography::STPointFromText
  • 字段.STDistance
  • POINT

相關閱讀

相關文章
相關標籤/搜索