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)