Home Forums SQL Server 2008 SQL Server 2008 - General Optimize query for finding nearest airport based on latitude and longitude using STDistance RE: Optimize query for finding nearest airport based on latitude and longitude using STDistance

  • Hello guys.

    I try to somehow copy what dwain.c did in his query. I was just wondering if there's a possibility that the orig lat and long would be the same as the destination lat and long. Like the airport they flew from would also be their destination.

    I have my code as this: I just wanted to ask if the code for getting the @StartLat, @StartLong, @EndLat, and @EndLong would work?

    DECLARE @StartLat DECIMAL(8, 5)

    , @EndLat DECIMAL(8, 5)

    , @StartLong DECIMAL(8, 5)

    , @EndLong DECIMAL(8, 5)

    , @LatDiff DECIMAL(8, 5)

    , @LongDiffDECIMAL(8, 5);

    SELECT TOP(1) @StartLat = Latitude, @StartLong = Longitude

    FROMdbo.Log_Details

    ORDER BY Latitude, Longitude;

    SELECT TOP(1) @EndLat = Latitude, @EndLong = Longitude

    FROMdbo.Log_Details;

    ORDER BY Latitude DESC, Longitude DESC;

    SELECT @LatDiff= ABS(@StartLat - @EndLat), @LongDiff= ABS(@StartLong - @EndLong);

    SELECT Log_Detail_ID, Latitude, Longitude, Airport_Latitude, Airport_Longitude, Distance

    FROMdbo.Log_Details

    CROSS APPLY(SELECT TOP(1) *, Distance = Airport_Geography.STDistance(GEOGRAPHY::Point(Latitude, Longitude, 4326))

    FROMdbo.Airports WHERE Airport_Latitude BETWEEN Latitude - @LatDiff AND Latitude + @LatDiff

    AND Airport_Longitude BETWEEN Longitude - @LongDiff AND Longitude + @LongDiff

    ORDER BY Airport_Geography.STDistance(GEOGRAPHY::Point(Latitude, Longitude, 4326))) AS a;

    Thank you.