I am trying to build a query, but I am having some difficulty.
I have a SQL Server 2008 database with a table that includes, among other fields, a geography field that describes road segments. (This data has been imported from TIGER/Line data from the U.S. Census.)
I have another fixed point describing a user’s location. I want to find the closest road segment in the database to that point, but I can’t seem to figure out how to accomplish this. Furthermore, I want to find the closest point on that segment to the user location point. This is what I want to select and return back in my query.
Does anyone have any experience with the geography/geometry functionality that can help me?
Thanks!
You can store your objects in a
GEOGRAPHYcolumn and create aSPATIAL INDEXover this column.Unfortunately,
SQL Serverimplements spatial indexes by tiling the surface and storing the tile identifiers in a plainB-Treeindex, so plainORDER BY STDistancewon’t work (well, it will work but won’t use the index).Instead, you’ll have to make a query similar to this:
This way,
SQL Serverwill first search roads within1kilometer from your point, then within2kilometers, etc., each time using the index.Update:
If you have multiple points in a table and want to find the closest point for each of them: