I want to perform a query (to pull locations within a given distance from a specified lat/lng) against a MS SQL 2008 Server, no geo field types:
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
This is the haversine formula described here. I’d like to call the query, probably setup as a stored procedure, using LINQ – pulled into an IEnumerable list.
The table essentially looks like this:
Locations Table
- Id – long PK
- Name – nvarchar…
- Lat
- Lng …
I’m not familiar with the math functions in MS SQL, the query example is MySQL. Will this query port to MS SQL well? Am I asking for problems attempting to do this?
The query you’ve posted should work reasonably well.
However, if you are in the position where you can change your data schema then SQL Server has some native Geography types – and if you could use these then there are built-in functions and built-in indexing which would allow you to execute this type of query much more efficiently – see http://www.microsoft.com/sqlserver/2008/en/us/spatial-data.aspx