本文介绍了一个SQL表的所有Lat Lng在15公里之内到一个不同表的每个Lat Lng-sql 2008的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SQL 2008
我有两个桌子.一张桌子(A)大约有4000个位置.另一个表(B)具有800个经纬度的位置.
I have two tables. One table (A) have around 4000 locations with lat lng. Another table (B) having 800 locations with lat lng.
我需要表B中的每个纬度以及半径15 Km之内的所有相应纬度.
I need each lat lng of Table B with all corresponding lat lngs within 15 Km of radius.
我正在使用sql 2008,这是地理查询的新手.
I am using sql 2008 and very new to geographical queries.
推荐答案
/*
Assuming Your tables are like so
*/
IF OBJECT_ID('#xLocation1') IS NOT NULL
DROP TABLE #xLocation1
CREATE TABLE #xLocation1 (
Id INT IDENTITY(1,1) CONSTRAINT PK_Location_1 PRIMARY KEY--Reqire this for Geog Spatial Index
,LocationId INT
,Latitude FLOAT NULL
,Longitude FLOAT NULL
,Radius INT NULL
,GeogPoint GEOGRAPHY NULL
)
IF OBJECT_ID('#xLocation2') IS NOT NULL
DROP TABLE #xLocation2
CREATE TABLE #xLocation2 (
Id INT IDENTITY(1,1) CONSTRAINT PK_Location_2 PRIMARY KEY--Reqire this for Geog Spatial Index
,LocationId INT
,Latitude FLOAT NULL
,Longitude FLOAT NULL
,Radius INT NULL
,GeogPoint GEOGRAPHY NULL
)
DECLARE @Radius INT = 15 --KM
/*
Create GEOGRAPHY POINT datatypes
*/
UPDATE #xLocation1
SET
GeogPoint = GEOGRAPHY::STGeomFromText('POINT(' + CAST(ISNULL(Longitude,'') AS VARCHAR(20)) + ' ' + CAST(ISNULL(Latitude,'') AS VARCHAR(20)) + ')', 4326)
UPDATE #xLocation2
SET
GeogPoint = GEOGRAPHY::STGeomFromText('POINT(' + CAST(ISNULL(Longitude,'') AS VARCHAR(20)) + ' ' + CAST(ISNULL(Latitude,'') AS VARCHAR(20)) + ')', 4326)
/*
CREATE SPATIAL INDEXes
*/
CREATE SPATIAL INDEX [SDX_Location1_GeogPoint_x1] ON #xLocation1 ( [GeogPoint] )
USING GEOGRAPHY_GRID
WITH
( GRIDS=(LEVEL_1 = HIGH,LEVEL_2 = HIGH,LEVEL_3 = HIGH,LEVEL_4 = HIGH)
, CELLS_PER_OBJECT = 64
, PAD_INDEX = OFF
, SORT_IN_TEMPDB = OFF
, DROP_EXISTING = OFF
, ALLOW_ROW_LOCKS = ON
, ALLOW_PAGE_LOCKS = ON
)
CREATE SPATIAL INDEX [SDX_Location2_GeogPoint_x2] ON #xLocation2 ( [GeogPoint] )
USING GEOGRAPHY_GRID
WITH
( GRIDS=(LEVEL_1 = HIGH,LEVEL_2 = HIGH,LEVEL_3 = HIGH,LEVEL_4 = HIGH)
, CELLS_PER_OBJECT = 64
, PAD_INDEX = OFF
, SORT_IN_TEMPDB = OFF
, DROP_EXISTING = OFF
, ALLOW_ROW_LOCKS = ON
, ALLOW_PAGE_LOCKS = ON
)
/*
Find where locations from each table are within @Radius of each other
*/
SELECT *
FROM
#xLocation1 X
INNER JOIN
#xLocation2 P ON X.GeogPoint.STDistance(P.GeogPoint) <= @Radius
这篇关于一个SQL表的所有Lat Lng在15公里之内到一个不同表的每个Lat Lng-sql 2008的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!