Query processor could not produce a query plan because of the hints defined in this query. Resubmit the query and without using SET FORCEPLAN
From here:
The following requirements must be met for a Nearest Neighbor query to use a spatial index:
- A spatial index must be present on one of the spatial columns and the STDistance() method must use that column in the WHERE and ORDER BY clauses.
- The TOP clause cannot contain a PERCENT statement.
- The WHERE clause must contain a STDistance() method.
- If there are multiple predicates in the WHERE clause then the predicate containing STDistance() method must be connected by an AND conjunction to the other predicates. The STDistance() method cannot be in an optional part of the WHERE clause.
- The first expression in the ORDER BY clause must use the STDistance() method.
- Sort order for the first STDistance() expression in the ORDER BY clause must be ASC.
- All the rows for which STDistance returns NULL must be filtered out.
So, this should work:
DECLARE @g geography;
declare @point nvarchar(50) =''
declare @i int =0,
@lat decimal(8,6) =0.0,
@long decimal(8,6) =0.0,
@start datetime = getdate()
set @lat =(select (0.9 -Rand()*1.8)*100)
set @long =(select (0.9 -Rand()*1.8)*100)
set @point = (select 'POINT('+CONVERT(varchar(10), @lat)+ ' '
+CONVERT(varchar(10), @long)+')')
SET @g = geography::STGeomFromText(@point, 4326);
SELECT TOP 1000
@lat,
@long,
@g.STDistance(st.[coord]) AS [DistanceFromPoint (in meters)]
, st.[coord]
, st.id
FROM Temp st with(index([SpatialIndex_1]))
WHERE @g.STDistance(st.[coord]) IS NOT NULL
ORDER BY @g.STDistance(st.[coord]) asc
You can check that it is using the spacial index even the WITH INDEX
hint is removed.