简体   繁体   中英

How do I write a stored procedure in SQL Server that would increment IDs based on a point location (spatial intersection) within a polygon

I have two tables in SQL server - one is a point feature class and another is a polygon. Essentially assets that fall within polygons that have ID 0-9.

What I would like to do is write a stored procedure/trigger that when a new asset is added the table is queried to see the last numeric ID assigned for that zone (ie if the last feature in zone 2 was 2113 the next would be 2114). The first number in the numeric ID would always be the polygon containing the point (zone 0 would always be 0111,0112; zone one would alwasy be 1111,1112; etc.)

create table [point feature class AKA assets] ([point] geometry)
insert [point feature class AKA assets]
select geometry::STPointFromText('POINT (1 1)', 0)
insert [point feature class AKA assets]
select geometry::STPointFromText('POINT (2 2)', 0)
insert [point feature class AKA assets]
select geometry::STPointFromText('POINT (3 3)', 0)
insert [point feature class AKA assets]
select geometry::STPointFromText('POINT (4 4)', 0)  
insert [point feature class AKA assets]
select geometry::STPointFromText('POINT (5 5)', 0)  
insert [point feature class AKA assets]
select geometry::STPointFromText('POINT (8 8)', 0)  
insert [point feature class AKA assets]
select geometry::STPointFromText('POINT (10 10)', 0)    
select * from [point feature class AKA assets]

create table [zone] ([numeric ID assigned for that zone] int, [polygon] geometry)
insert zone 
select 0, geometry::STPolyFromText('POLYGON ((0 0, 3 0, 3 3, 0 3, 0 0))', 0) 
insert zone 
select 1, geometry::STPolyFromText('POLYGON ((5 5, 8 5, 8 8, 5 8, 5 5))', 0) 
insert zone 
select 2, geometry::STPolyFromText('POLYGON ((9 9, 12 9, 12 12, 9 12, 9 9))', 0) 

select [point].ToString() AS 'asset', 
CAST([numeric ID assigned for that zone] AS varchar) + 
    CAST(ROW_NUMBER() OVER(PARTITION BY [numeric ID assigned for that zone] ORDER BY [point].ToString())AS varchar) AS '"numeric" ID'
from [point feature class AKA assets]
join [zone] on [point].STIntersects([polygon]) = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM