I am working with a 'NearBy Properties' Module in C#,Asp.net,.net ver 2.0 and MSSQL 2005.My requirement is like ,
I pass a specific Lat
and Lan
value to DB,It should fetch me 35 nearest properties by comparing the passed Lat
Lan
with the Lat
Lan
values already saved in DB.Can this be done in the SQL part itself ?
I can do this in Asp.net
part by
- looping through all the rows in a DataTable,then
Creating an extra field called 'Miles' in DataTable and inserting Km values in to it,like this
public decimal calcDistance(decimal latA, decimal longA, decimal latB, decimal longB) { double theDistance = (Math.Sin(DegreesToRadians(latA)) * Math.Sin(DegreesToRadians(latB)) + Math.Cos(DegreesToRadians(latA)) * Math.Cos(DegreesToRadians(latB)) * Math.Cos(DegreesToRadians(longA - longB))); return Convert.ToDecimal((RadiansToDegrees(Math.Acos(theDistance)))) * 69.09M * 1.6093M; }
Then Sorting the DataTable with 'Miles' field,and fetching top 35 rows from DataTable.
The Problem is,
I have to fetch all the DB rows in to asp part and then do a for loop and then do a sort,this takes up lot of time and resources,Is there any way I can execute this in the SQL part itself ?
SOLUTION
I tweaked @Bacon Bits answer below as
SELECT PM.Id AS PropertyId,PM.Address,PM.PropertyImage, ROUND((DEGREES(ACOS(SIN(RADIANS('9.98')) * SIN(RADIANS(PM.Latitude)) + COS(RADIANS('9.98')) * COS(RADIANS(PM.Latitude)) * COS(RADIANS(76.27999999999997 - PM.Longitude)))) * 69.09 * 1.6093),0) AS Miles
FROM Tbl_PropertyMaster PM
INNER JOIN dbo.Tbl_PropertyApproval AS PA
ON PA.PropertyId = PM.Id
WHERE PM.IsDeleted='False' AND PM.Enabled='True' and PA.Action='Approved' AND ROUND((DEGREES(ACOS(SIN(RADIANS('9.98')) * SIN(RADIANS(PM.Latitude)) + COS(RADIANS('9.98')) * COS(RADIANS(PM.Latitude)) * COS(RADIANS(76.27999999999997 - PM.Longitude)))) * 69.09 * 1.6093),0) < 1000
ORDER BY Miles DESC