SQL Server中的空间连接

gzszwxb4  于 2022-12-10  发布在  SQL Server
关注(0)|答案(1)|浏览(160)

I come from a mining and exploration background. I have a list of points (with ID and X and Y coordinates).
Example
I have another table which contains polygons (claim numbers). I am trying to find out which points fall within which polygons. My coordinates are in UTM Projection.
Thank you in advance!
I was trying the following code however my query is not returning results.

SELECT 
      pg.claim_number, 
      p.DHId 
FROM leasehold as pg
JOIN
(SELECT 
     DHId, 
     X, 
     Y,
     geometry::STPointFromText('POINT(',X,' ',Y,'), 0) AS [geom]
 FROM collar 
      WHERE X is not null AND 
      Y is not null AND 
      claim_number is null) AS p
ON pg.Shape.STIntersects(p.geom) = 1

I was expecting to get a list with claim_number from polygon table which each DHId from point table intersects or falls within.

5uzkadbs

5uzkadbs1#

It looks like there just a syntax/quoting issue. I cleaned it up a bit and replaced STPointFromText with Point which is an MS-specific extension but doesn't require you to create WKT just to get a point. But that's really all I changed - I'd expect your general approach to work.

SELECT 
      pg.claim_number, 
      p.DHId 
FROM leasehold as pg
JOIN (
    SELECT 
        DHId, 
        X, 
        Y,
        geometry::Point(X, Y, 0) AS [geom]
    FROM collar 
    WHERE X is not null AND 
        Y is not null AND 
        claim_number is null
) AS p
    ON pg.Shape.STIntersects(p.geom) = 1;

That said, I would expect this to not be super performant. You're creating the points on the fly and so will be incurring that cost at run time. As such, there's no way to put a spatial index on that data. If you can, I'd suggest adding a column to your collar table that is the geometry point and, as I implied, put a spatial index on it. Also, if there's not an index on the leasehold.Shape column, I'd put one there as well.

相关问题