I am having serious performance issues with a spatial update query in SQL Server 2008 (not R2) using STDistance(). The goal is simple enough: I have a table with 120,000 records, Houses with the column NearestLibrary. I have a second table with 12 records, Libraries with the column Name. Both tables have a geography column LatLngGeography. I want to update Houses.NearestLibrary with the name of the closest library from Libraries.
This query takes around 50 seconds to run:
UPDATE Houses
SET NearestLibrary = (
SELECT TOP 1 Name
FROM Libraries
ORDER BY Houses.LatLngGeography.STDistance(Libraries.LatLngGeography)
)
That would almost be acceptable, except that when I run it for Parks instead of Libraries where I have about 100 parks, it takes almost 10 times as long. Both tables have properly constructed spatial indexes named IX_Houses_LatLngGeography and IX_Libraries_LatLngGeography respectively but thus far I have been unable to work out how make my query use them.
Is there a way to improve the performance of my query?
Use an “Index Hint”.