2013-07-25 63 views
1

我嘗試計算並排序用戶和商場位置之間的距離(最近)。我需要爲每個商場行做到這一點,但由於性能問題,我不想使用「while」。我該怎麼辦?SQL選擇,執行並顯示所有行

下面的代碼只顯示執行後的最後一行。

@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) 

回答

1

你可以把計算到的MALLSELECT。這會給你從@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年