一系列几何数据类型的最小和最大点

时间:2012-11-27 15:31:59

标签: sql sql-server-2008-r2 geometry

在将一系列Shapefile引入SQL Server 2008R2之后,我们希望获取表格中一系列多边形的最小和最大点数。

如果没有像SQL Server 2008R2中的STExtent这样的聚合函数,如何确定最小和最大点?

此博客文章指出了一系列选项:
http://alastaira.wordpress.com/2011/07/26/determining-the-geographic-extent-of-spatial-features-in-a-sql-server-table/

  • 选项#1:使用光标
  • 选项#2:CLR功能
  • 选项#3:CTE
  • 选项#4:持久信封

一个例子:

BEGIN TRAN
  CREATE TABLE #Lines
  (
    ID INT IDENTITY(1,1)
    ,Poly GEOMETRY NULL
  );

  INSERT INTO #Lines
    (Poly)
  VALUES
    (geometry::STGeomFromText('LINESTRING(0 0, 2 3)', 0));

  INSERT INTO #Lines
    (Poly)
  VALUES
    (geometry::STGeomFromText('LINESTRING(1 1, 2 4)',0));

  --How can i get the min and max x and y points?
      --(e.g. for this example Xmin = 0, Xmax = 2, Ymin = 0, Ymax = 4)


  DROP TABLE #Lines 
COMMIT

2 个答案:

答案 0 :(得分:4)

如果您使用SQL Server 2008,请使用:

select MIN((<geom_col>).STEnvelope().STPointN(1).STX) as xmin,
MAX((<geom_col>).STEnvelope().STPointN(3).STX) as xmax,
MIN((<geom_col>).STEnvelope().STPointN(1).STY) as ymin,
MAX((<geom_col>).STEnvelope().STPointN(3).STY) as ymax from <your table>;

SQL Server 2012有一个新功能UnionAggregate。所以另一种选择是:

select  geometry::UnionAggregate (<geom_col>).STEnvelope().STPointN(1).STX as xmin,
geometry::UnionAggregate (<geom_col>).STEnvelope().STPointN(3).STX as xmax,
geometry::UnionAggregate (<geom_col>).STEnvelope().STPointN(1).STY as ymin,
geometry::UnionAggregate (<geom_col>).STEnvelope().STPointN(3).STY as ymax from <your table>

答案 1 :(得分:1)

我同意前面提到的(和linked)博客文章的作者,鉴于数据没有变化,持久性信封是一个很好的解决方案。

下面我编辑了一个示例来回答该实现的问题。

BEGIN TRAN
  CREATE TABLE #Lines
  (
    ID INT IDENTITY(1,1)
    ,Poly GEOMETRY NULL
  );

 INSERT INTO #Lines
  (Poly)
 VALUES
  (geometry::STGeomFromText('LINESTRING(0 0, 2 3)', 0));

 INSERT INTO #Lines
  (Poly)
 VALUES
  (geometry::STGeomFromText('LINESTRING(1 1, 2 4)',0));


 --Using option 4 of persisted envelopes

 ALTER TABLE #Lines
   ADD
     MinX AS (CONVERT(int, Poly.STEnvelope().STPointN((1)).STX, 0)) PERSISTED,
     MinY AS (CONVERT(int, Poly.STEnvelope().STPointN((1)).STY, 0)) PERSISTED,
     MaxX AS (CONVERT(int, Poly.STEnvelope().STPointN((3)).STX, 0)) PERSISTED,
     MaxY AS (CONVERT(int, Poly.STEnvelope().STPointN((3)).STY, 0)) PERSISTED;

 SELECT
   MIN(MinX) AS [X Minimum]
   ,MIN(MinY) AS [Y Minimum]
   ,MAX(MaxX) AS [X Maximum]
   ,MAX(MaxY) AS [Y Maximum]    
 FROM #Lines

 DROP TABLE #Lines 
COMMIT