Calculates the distance between two coordinate points (longitude, latitude) of the Earth SQL function

Source: Internet
Author: User
Tags cos sin

Go  -Calculates the distance between two coordinate points (longitude, latitude) on the earth SQL function--lordbaby--: www.aspbc.com CREATE function [dbo].[ Fngetdistance] (@LatBegin Real, @LngBegin Real, @LatEnd Real, @LngEnd Real) RETURNS FLOAT  asbegin  -distance (km)  DECLARE @Distance Real  DECLARE @EARTH_RADIUS real  SET @EARTH_RADIUS = 6378.137    DECLARE @RadLatBegin real,@ Radlatend Real, @RadLatDiff Real, @RadLngDiff real  Set @RadLatBegin = @LatBegin *pi ()/180.0    SET @RadLatEnd = @ Latend *pi ()/180.0    Set @RadLatDiff = @RadLatBegin-@RadLatEnd    Set @RadLngDiff = @LngBegin *pi ()/180.0-@LngEnd *pi ()/180.0     SET @Distance = 2 *asin (SQRT (POWER (SIN (@RadLatDiff/2), 2) +cos (@RadLatBegin) *cos (@RadLatEnd) *power ( SIN (@RadLngDiff/2), 2)))  SET @Distance = @Distance * @EARTH_RADIUS    --set @Distance = Round (@Distance * 10000)/ 10000    RETURN @DistanceEND

Here's how to use it:

1 SELECTFROM商家表名 WHEREdbo.fnGetDistance(121.4625,31.220937,longitude,latitude) < 5

(Mouse over the code, there will be four icons at the top of the code, the first one is to view the source code, the second is to copy the code, the third is to print the code, the fourth is to help)
The longitude,latitude here are the longitude and latitude fields of the hotel, and 121.4625,31.220937 is the longitude of the current customer where the phone is located, and the latter 5 is within 5 km.

Lordbaby also told me that in the SQL2008 database, you can directly use the geography data function to solve, see http://msdn.microsoft.com/zh-cn/library/bb933952 (v=sql.100). aspx.

Calculates the distance between two coordinate points (longitude, latitude) of the Earth SQL function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.