我有一张桌子
具有列邮政编码的人
与一个zipcode表相关,该表包含zip码作为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
我试过这只是为了过滤参数化搜索范围之外的人,但它不起作用。说“关键字附近的语法不正确”,其中“
甚至不包括我想要输入zipcode的参数,而不是:
其中zipcode ='20013'
我想要像:
其中zipcode = @zipcode
但它说我需要声明zscalar变量@zipcode并且无论我在哪里尝试这样做...我一直得到同样的错误
感谢您的帮助
答案 0 :(得分:1)
您在“where”之前使用“order by”子句是问题之一,并且您不能在条件是另一个问题的地方使用别名。请尝试以下查询:
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)