SQL Server – Validate Geometry Polygon Data Using Stored Procedure

geometryspatialsql serverstored-procedures

We are using a SQL Server Spatial database with the following table setup:

  • SRID of 27700
  • geometry_column of ogr_geometry
  • geometry_type of POLYGON

I am using a SQL Server stored procedure to perform the following test:

geometry::STGeomFromText(@poly, @srid).STIsValid();

When tested the using the following it correctly returns true:

.Parameters.Append .CreateParameter("@poly ", 200, 1, 50, "POLYGON((1 1, 3 3, 3 1, 1 1))")
.Parameters.Append .CreateParameter("@srid ", 3, 1, 10, 0)

When I run the live data (held in the recordset rs) it always returns false even though I suspect about half the polygons should be true:

.Parameters.Append .CreateParameter("@poly ", 200, 1, 1000000000, rs("ogr_geometry"))
.Parameters.Append .CreateParameter("@srid ", 3, 1, 10, 27700)

Am I doing anything that is obviously wrong or could it be the case that although some of the geometry works in our system none of it is strictly valid?

I have prepared a ZIP file with an example polygon that works and one that does not. Both are being flagged by SQL Server as invalid.

Best Answer

This issue was being caused because the ogr_geometry coming from the recordset had not been cast to a string.

When I changed the field in the recordset to ogr_geometry.ToString() AS sGeometry and used sGeometry instead of ogr_geometry all worked as expected.