1

我有一张桌子

具有列邮政编码的人

这与一个 zipcodes 表相关,该表具有 zipcode 作为 id 和一个纬度和经度列。

我发现了一系列使用纬度和经度计算球体距离(基本上是邮政编码)的函数。我对 sql 比较陌生,想知道如何在存储过程中使用这些函数。

纬度函数:

        ALTER Function [dbo].[LatitudePlusDistance](@StartLatitude Float, @Distance Float) Returns Float
As
Begin
    Return (Select @StartLatitude + Sqrt(@Distance * @Distance / 4766.8999155991))
End

经度函数:

    ALTER FUNCTION [dbo].[LongitudePlusDistance]
(
    @StartLongitude float,
    @StartLatitude float,
    @Distance float
)
    RETURNS Float
    AS
begin

RETURN (select @startLongitude + sqrt(@Distance * @Distance/(4784.39411916406*Cos(2*@StartLatitude/114.591559026165)*Cos(2*@StartLatitude/114.591559026165))))
END
begin

RETURN (select @startLongitude + sqrt(@Distance * @Distance/(4784.39411916406*Cos(2*@StartLatitude/114.591559026165)*Cos(2*@StartLatitude/114.591559026165))))
END`

计算距离函数

    `ALTER Function [dbo].[CalculateDistance]
    (@Longitude1 Decimal(8,5),
    @Latitude1   Decimal(8,5),
    @Longitude2  Decimal(8,5),
    @Latitude2   Decimal(8,5))
Returns Float
As
Begin
Declare @Temp Float

Set @Temp = sin(@Latitude1/57.2957795130823) * sin(@Latitude2/57.2957795130823) + cos(@Latitude1/57.2957795130823) * cos(@Latitude2/57.2957795130823) * cos(@Longitude2/57.2957795130823 - @Longitude1/57.2957795130823)

if @Temp > 1
    Set @Temp = 1
Else If @Temp < -1
    Set @Temp = -1

Return (3958.75586574 * acos(@Temp) )

End`

我试过这样的东西......

    Declare @Longitude Decimal(8,5)
Declare @Latitude Decimal(8,5)

Select  @Longitude = Longitude,
        @Latitude = Latitude
From    ZipCodes
Where   ZipCode = '20013'

    Declare @Distance int

Select  persons.personName, ZipCodes.City,  dbo.CalculateDistance(@Longitude, @Latitude, ZipCodes.Longitude, ZipCodes.Latitude) As Distance
From    persons
        Inner Join ZipCodes
            On persons.zipcode = ZipCodes.ZipCode
Order By dbo.CalculateDistance(@Longitude, @Latitude, ZipCodes.Longitude, ZipCodes.Latitude)
    WHERE dbo.CalculateDistance(@Longitude, @Latitude, ZipCodes.Longitude, ZipCodes.Latitude) As Distance <= @Distance

我尝试这样做只是为了过滤参数化搜索半径之外的人,但它不起作用。说在关键字“where”附近有一个“不正确的语法”

这甚至不包括我希望为邮政编码输入参数的愿望,而不是:

其中邮政编码 = '20013'

我想要类似的东西:

其中邮政编码 = @zipcode

但它说我需要声明 zscalar 变量@zipcode,无论我在哪里尝试这样做......我都会收到同样的错误

谢谢您的帮助

4

1 回答 1

1

您在“where”之前使用“order by”子句,这是问题之一,您不能在 where 条件是另一个问题中使用别名。请尝试以下查询:

Declare @Longitude Decimal(8,5)
Declare @Latitude Decimal(8,5)

Select  @Longitude = Longitude,
        @Latitude = Latitude
From    ZipCodes
Where   ZipCode = '20013'

Declare @Distance int
set @Distance = 5

Select  persons.personName, ZipCodes.City,  dbo.CalculateDistance(@Longitude, @Latitude,    ZipCodes.Longitude, ZipCodes.Latitude) As Distance
From    persons Inner Join ZipCodes On persons.zipcode = ZipCodes.ZipCode
WHERE dbo.CalculateDistance(@Longitude, @Latitude, ZipCodes.Longitude, ZipCodes.Latitude) <= @Distance
Order By dbo.CalculateDistance(@Longitude, @Latitude, ZipCodes.Longitude, ZipCodes.Latitude)
于 2013-07-04T04:03:59.077 回答