2012-08-25 14 views
0

我正在從windows phone 7.5獲取位置更新到我的sql server 2008 R2數據庫。手機在車裏,也可以作爲跟蹤設備使用。如何在SQL Server 2008 R2的郵政編碼表中查找最近的地理位置

例如:這個位置(緯度:51.5557830164189經度:0.0711440443992739)是我從手機收到的。現在我想找到最近的位置或郵政編碼對我的郵政編碼表中的這個位置,這是幾乎有1.7米的記錄。

我郵政編碼表的定義是

CREATE TABLE [dbo].[PostCode1](
    [Postcode] [nvarchar](50) NOT NULL, 
    [Coordinates] [geography] NOT NULL, 
CONSTRAINT [PK_PostCode1] PRIMARY KEY CLUSTERED 
(
    [Postcode] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

我已經使用Google,但無法找到答案試過很多博客的

有人能指導我如何使用查詢實現這一目標,我需要表中只有1條記錄,時間更少。

謝謝

回答

2

我在下面發現這個功能非常有幫助。我修改了它,所以它以英里而不是公里爲單位。

您可以將此用作構建返回最近郵政編碼的過程的基礎。

如果您創建視圖/ @temptable,您可以計算出點到點的距離,然後按最短距離的頂部1進行過濾。

/****** Object: UserDefinedFunction [dbo].[DISTANCE] ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER function [dbo].[DISTANCE] 
    (
    @Latitude1 float, 
    @Longitude1 float, 
    @Latitude2 float, 
    @Longitude2 float 
    ) 
returns float 
as 
/* 
fUNCTION: F_GREAT_CIRCLE_DISTANCE 

    Computes the Great Circle distance in kilometers 
    between two points on the Earth using the 
    Haversine formula distance calculation. 

Input Parameters: 
    @Longitude1 - Longitude in degrees of point 1 
    @Latitude1 - Latitude in degrees of point 1 
    @Longitude2 - Longitude in degrees of point 2 
    @Latitude2 - Latitude in degrees of point 2 

*/ 
begin 
declare @radius float 

declare @lon1 float 
declare @lon2 float 
declare @lat1 float 
declare @lat2 float 

declare @a float 
declare @distance float 

-- Sets average radius of Earth in Kilometers 
set @radius = 3959.0E 

-- Convert degrees to radians 
set @lon1 = radians(@Longitude1) 
set @lon2 = radians(@Longitude2) 
set @lat1 = radians(@Latitude1) 
set @lat2 = radians(@Latitude2) 

set @a = sqrt(square(sin((@[email protected])/2.0E)) + 
    (cos(@lat1) * cos(@lat2) * square(sin((@[email protected])/2.0E)))) 

set @distance = 
    @radius * (2.0E *asin(case when 1.0E < @a then 1.0E else @a end)) 

return @distance 

end 
+1

要返回最近的郵政編碼,您需要對郵政編碼進行經緯度查詢。這個功能如何幫助? – Ben