Skip to main content

MS SQL Server 2008 - Stored Procedure for Getting X meter radious of spacial data from a point

Stored Procedure to find data for x meter radious from a point using SQL Server geography data.

Create Procedure GetXMeterRadiousData
(
 @RadiousInMeter INT=0,
 @Point GEOGRAPHY=NULL,
 @Mode VARCHAR(10)='DISTANCE'
)
AS
BEGIN
DECLARE @g geography
IF (@Mode='DISTANCE')
  -- Using Distance method
     BEGIN
 -- Get the point
            SELECT @g = geo FROM SpacialDataTable
            WHERE geo = @Point
            -- Get the results, radius @RadiousInMeter
           SELECT * FROM SpacialDataTable
           WHERE @g.STDistance(geo) <= @RadiousInMeter
   
     END
ELSE
  -- Using INTERSECTS method
      BEGIN
 -- Get the center buffer, @RadiousInMeter radius
 SELECT @g = geo.STBuffer(@RadiousInMeter) FROM SpacialDataTable
 WHERE geo = @Point
 -- Get the results within the buffer
 SELECT * FROM SpacialDataTable WHERE @g.STIntersects(geo) = 1
      END
END

Comments