Leveraging SQL Server's Geography Data Type for Distance Calculations
Determining the distance between two points specified by latitude and longitude necessitates a specialized approach. SQL Server, starting with version 2008, offers the geography
data type, a powerful tool for handling and analyzing geographic information.
The geography::Point
method constructs a geography
object for each point, employing SRID 4326, which corresponds to WGS84 (World Geodetic System 1984). Once these objects are created, the STDistance
method efficiently calculates the distance:
<code class="language-sql">DECLARE @orig geography = geography::Point(@orig_lat, @orig_lng, 4326); SELECT *, @orig.STDistance(geography::Point(dest.Latitude, dest.Longitude, 4326)) AS distance --INTO #includeDistances FROM #orig dest</code>
This yields a precise distance in meters. For example, given sample data:
<code>Latitude Longitude Distance 53.429108 -2.500953 85.2981833133896</code>
The calculated distance will be approximately 85.3 meters, providing a considerably more accurate result than simpler methods. The geography
data type is thus a robust and efficient solution for geospatial applications in SQL Server, simplifying complex calculations while enhancing accuracy.
The above is the detailed content of How Can I Calculate the Distance Between Two Latitude/Longitude Points in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!