SQL Select 不使用 MakeValid 的有效几何

SQL Select valid Geometries without using MakeValid

我有大量 table 数据,其中包含 SQL 几何值。根据 OGC (Geometry.STIsValid()). This causes many of my Geometries to throw an error when I check the Geometry.STGeometryType()

,许多行包含 "not-well-formed" 几何图形

当我使用这个 SQL 查询时,我错误地假设它会遗漏无效的几何图形:

SELECT [Geometry] FROM Features 
  WHERE [Geometry] IS NOT NULL
    AND [Geometry].STIsValid() = 1
    AND [Geometry].STGeometryType() = 'Point'

STGeometryType() 函数抛出此错误:

A .NET Framework error occurred during execution of user-defined routine or aggregate "geometry": System.ArgumentException: 24144: This operation cannot be completed because the instance is not valid. Use MakeValid to convert the instance to a valid instance. Note that MakeValid may cause the points of a geometry instance to shift slightly. System.ArgumentException: at Microsoft.SqlServer.Types.SqlGeometry.ThrowIfInvalid() at Microsoft.SqlServer.Types.SqlGeometry.STGeometryType()

我在使用子查询时遇到同样的错误:

SELECT G.* FROM (
  SELECT [Geometry] FROM Features 
    WHERE [Geometry] IS NOT NULL
     AND [Geometry].STIsValid() = 1
) AS G
   WHERE G.[Geometry].STGeometryType() = 'Point'

使用 Geometry.MakeValid() 函数不是一个可行的解决方案,我不能让 SQL 服务器任意更改我的几何图形,但我需要能够分辨出像这样的视图它们是什么类型:

CREATE VIEW vw_Points
AS
  SELECT [Geometry] FROM vwValidFeatures 
    WHERE [Geometry].STGeometryType() = 'Point'

有人对此有更好的解决方案或解决方法吗?

我能想出的最佳解决方案是 select 所有几何体 STAsText() 然后解析字符串,因为 STAsText() 不会抛出任何错误,如果无效。

这是我自己能找到的最佳解决方案:

CREATE VIEW [vwValidGeometries]
AS
  SELECT A.* FROM (
    SELECT 
        Id,
        CASE [Geometry].STIsValid() 
           WHEN 1 THEN [Geometry] 
           ELSE NULL 
        END AS 'Geo'
    FROM Features
  )
    WHERE Geo IS NOT NULL

然后:

SELECT * FROM vwValidGeometries WHERE Geo.STGeometryType() = 'Point'

这充分隔离了 STIsValid() 函数,以至于它不会被任何在几何无效时会抛出错误的函数触及。

我在 MSDN 上找到了这个答案。