使用地理位置和距离从SQL Server数据库中选择记录

时间:2014-09-08 18:57:44

标签: sql sql-server select sqlgeography

我使用SQL Server地理数据类型来存储数据库中记录的位置。 我想选择给定位置给定距离内的所有记录:

DECLARE @location AS geography = geography::Point(@latitude, @longitude, 4326)
DECLARE @distance AS INT = 10000

SELECT * 
FROM records
WHERE records.location.STDistance(@location) <= @distance

我的测试数据库中有几十条记录,运行速度很快,我没有任何问题,但我知道WHERE子句正在对我数据库中的所有记录运行STDistance,一旦我有数千条记录记录,它会慢慢爬行。

有更好的方法吗?也许创建某种区域并首先在邻近区域中选择数据?

1 个答案:

答案 0 :(得分:1)

你绝对想要设置@Twelfth建议的空间索引。您还希望对范围进行搜索,而不是距离以更好地利用空间索引。

DECLARE @location AS geography = geography::Point(@latitude, @longitude, 4326)
DECLARE @distance AS INT = 10000
DECLARE @range AS geography = @location.STBuffer(@distance)

SELECT * 
FROM records
WHERE records.location.STIntersects(@Range) = 1