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

  • facturan.antonio (4/30/2012)


    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.

    I'm thinking that it will not. You need a flight time in your log table and then you could use that.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St