1

I try to calculate and order the distance(nearest) between an user and malls' location. I need to do it for every mall rows but I don't want to use "while" because of the performance issues. What should I do?

The code below only shows last row after execution.

@UserId INT
AS 
DECLARE
@UserLat DECIMAL(9,6),
@UserLon DECIMAL(9,6),
@MallLat DECIMAL(9,6),
@MallLon DECIMAL(9,6),
@geo1 geography,
@geo2 geography

SELECT TOP 1 @UserLat = l.Lat, @UserLon = l.Lon  FROM Location l WHERE l.UserId = @UserId ORDER BY l.LocationId DESC

SELECT @MallLat = m.MallLatitude, @MallLon = m.MallLongitude FROM Mall m

SET @geo1 = geography::Point(@UserLat, @UserLon, 4326)
SET @geo2 = geography::Point(@MallLat, @MallLon, 4326)

SELECT ROUND(@geo1.STDistance(@geo2)/1000,2)
4

1 回答 1

1

您可以将计算放入SELECTMALL@geo1这将为您提供从到每一MALL行的排序距离:

...
SELECT TOP 1 @UserLat = l.Lat, @UserLon = l.Lon  
FROM Location l WHERE l.UserId = @UserId 
ORDER BY l.LocationId DESC

SET @geo1 = geography::Point(@UserLat, @UserLon, 4326)

SELECT ROUND(@geo1.STDistance(
    geography::Point(MallLatitude, MallLongitude, 4326))/1000,2) AS distance 
FROM Mall
ORDER BY distance

我应该注意到我在 SQL Server 2012 上测试了这个,而不是你拥有的版本 - 2008。

于 2013-07-25T21:37:41.190 回答