发生了无效的浮点运算。 SQL Server 2008

时间:2012-01-12 14:53:56

标签: sql sql-server-2008 sql-server-2008-r2 floating-point-exceptions

我对此代码有一些奇怪的问题:如果我运行它如下所示,我会收到错误:

  

发生了无效的浮点运算。

但是,如果我将参数@Longitude更改为-98.508730 通知只更改了最后一位数,代码就可以了。

代码应该在某个LatLng点周围的@MilesRadius列出属性 @Latitude和@Longitude参数与表格地址中的经度和纬度字段的类型相同。

我可以在这做什么?感谢。

DECLARE @Latitude decimal (10,6);
DECLARE @Longitude decimal (10,6);
DECLARE @MilesRadius int;
SET @Latitude = 29.607654
SET @Longitude = -98.508731
SET @MilesRadius  = 5

SELECT     ADR.LineOne as address, 
           ADR.City as city,           
           ADR.Latitude as latitude,
           ADR.Longitude as longitude, 
           ((3959 * acos(cos(radians(@Latitude)) * cos(radians(ADR.Latitude)) * cos(radians(ADR.Longitude) - radians(@Longitude)) + sin(radians(@Latitude)) * sin(radians(ADR.Latitude))))) as distance
FROM       Shared.Address ADR
WHERE      ADR.Latitude IS NOT NULL AND 
           ADR.Longitude IS NOT NULL AND 
           (3959 * acos(cos(radians(@Latitude)) * cos(radians(ADR.Latitude)) * cos(radians(ADR.Longitude) - radians(@Longitude)) + sin(radians(@Latitude)) * sin(radians(ADR.Latitude)))) < @MilesRadius                       
ORDER BY distance

1 个答案:

答案 0 :(得分:11)

你正在使用的唯一一个返回域错误的函数是ACOS,并且当输入不在-1 to +1范围内时会发生这种情况,所以你可以摆弄这种情况(我假设是中间的)由于舍入错误,表达式类似于1.000000000001

SELECT     ADR.LineOne as address, 
           ADR.City as city,           
           ADR.Latitude as latitude,
           ADR.Longitude as longitude, 
           distance
FROM       Shared.Address ADR
CROSS APPLY (SELECT cos(radians(@Latitude)) * cos(radians(ADR.Latitude)) * cos(radians(ADR.Longitude) - radians(@Longitude)) + sin(radians(@Latitude)) * sin(radians(ADR.Latitude))) T(ACosInput)
CROSS APPLY (SELECT ((3959 * acos(CASE WHEN ABS(ACosInput) > 1 THEN SIGN(ACosInput)*1 ELSE ACosInput END)))) T2(distance)
WHERE      ADR.Latitude IS NOT NULL AND 
           ADR.Longitude IS NOT NULL AND 
           distance < @MilesRadius                       
ORDER BY distance