Saman Gholami
Saman Gholami

Reputation: 3512

Which Polygons contains the point

I'm using geometry::STPointFromText for getting a point from a text, and using geometry::STGeomFromText for creating my polygon. Now i have set of polygons of my Area in a table with this description :

Id       int       PK
Name     varchar
Polygon  varchar

Which area contains STPointFromText('POINT(12 31)',4326)? I need the query for this purpose.

Upvotes: 1

Views: 601

Answers (2)

Ben Thul
Ben Thul

Reputation: 32707

If you add a computed column to your table that represents the actual geometry object, you can do this in a set-based manner (which should scale a lot better than your cursor-based approach above). Persisting the column is optional, but will prevent the engine from having to create the geometry object on the fly each time the query is run. Something like:

alter table [Area] add g as as geometry::STGeomFromText([Polygon], 4326) persisted
DECLARE @point geometry = geometry::STPointFromText('POINT(539749 3953079)', 4326)
select * from [Area] where g.STIntersects(@point) = 1

Upvotes: 1

Saman Gholami
Saman Gholami

Reputation: 3512

I found a solution :

DECLARE @polygon geometry
DECLARE @selectedId int
DECLARE @point geometry = geometry::STPointFromText('POINT(539749 3953079)', 4326)
DECLARE geo_cur CURSOR FOR 
SELECT geometry::STGeomFromText('POLYGON(('+Polygon+'))', 4326),id FROM Area where Polygon is not null
OPEN geo_cur
FETCH NEXT FROM geo_cur
INTO @polygon,@selectedId

WHILE @@FETCH_STATUS = 0
    BEGIN

        IF @polygon.STIntersects(@point) = 1
            BEGIN
                PRINT @selectedId
            END

        FETCH NEXT FROM geo_cur
        INTO @polygon,@selectedId

    END
CLOSE geo_cur;
DEALLOCATE geo_cur;

Upvotes: 0

Related Questions