This is a seemingly simple SQL Server geometry question that I thought would have an out-of-the box solution, but I'm not having any luck finding one.
My intent is to select all the records within one table that have polygons that are nested (contained) within a larger polygon from another table. I had expected functions STWithin
and STContains
as being the solutions I needed, but unfortunately, both identify only the inner polygons within those nested in the larger polygon, not those nested polygons that are touching the boundary of the larger polygon. See image for example.
An alternative option that worked to my needs was STIntersection
. The problem with this function, however, is that it only returns the geometry column! I would like to obtain the record ID instead. Does anyone have a suggestion on how this can be done?
STWithin
:
select a.bg10 from
gis.usa_10_block_group a
join gis.usa_10_mkt_definition b
on a.shape.STWithin(b.shape) = 1
where b.mktname = 'Loop'
STContains
:
select a.bg10 from
gis.usa_10_block_group a
join gis.usa_10_mkt_definition b
on b.shape.STContains(a.shape) = 1
where b.mktname = 'Loop'
STIntersection
:
select a.shape.STIntersection(b.shape)
from gis.usa_10_block_group a
join gis.usa_10_mkt_definition b
on a.shape.STIntersects(b.shape) = 1
where b.mktname = 'Loop'
Edit:
One suggestion was to omit STIntersection
and use solely STIntersects
as follows:
STIntersects
:
select a.bg10
from gis.usa_10_block_group a
join gis.usa_10_mkt_definition b
on a.shape.STIntersects(b.shape) = 1
where b.mktname = 'Loop'
The problem with this approach, is that STIntersects
appears to select all polygons either within or outside and touching the larger polygon, not just those strictly within. See image for example.
STContains
orSTWithin
. Not really a nice hack, but will get you the results you want. The other option would be to do the STIntersects with a comparison of the Intersection area and the polygons area.