发生无效的浮点操作SQL

时间:2018-09-26 06:18:42

标签: sql sql-server

我正在使用SQL函数获取距离,但出现以下错误

  

发生无效的浮点运算。

这是我的功能

CREATE FUNCTION [dbo].[MeasureDistance] 
(
    -- Add the parameters for the function here
    @lat1 as float,
    @long1 as float,
    @lat2 as float,
    @long2 as float
)
RETURNS float
AS
BEGIN
    -- Declare the return variable here
declare @DegToRad as float
declare @Ans as float
declare @Miles as float

set @DegToRad = 57.29577951
set @Ans = 0
set @Miles = 0

if @lat1 is null or @lat1 = 0 or @long1 is null or @long1 = 0 or @lat2 is
null or @lat2 = 0 or @long2 is null or @long2 = 0
begin
return @Miles 
end
set @Ans = SIN(@lat1 / @DegToRad) * SIN(@lat2 / @DegToRad) + COS(@lat1 / @DegToRad ) * COS( @lat2 / @DegToRad ) * COS(ABS(@long2 - @long1 )/@DegToRad)
set @Miles = 3959 * ATAN(SQRT(1 - SQUARE(@Ans)) / @Ans)
set @Miles = CEILING(@Miles) * 1.609344
return @Miles
END

当我发送25.2048,55.2708纬度和经度时,出现以下错误。

2 个答案:

答案 0 :(得分:3)

使用real而不是float

CREATE FUNCTION [dbo].[MeasureDistance] 
(
    -- Add the parameters for the function here
    @lat1 as real,
    @long1 as real,
    @lat2 as real,
    @long2 as real
)
RETURNS real
AS
BEGIN
    -- Declare the return variable here
declare @DegToRad as real
declare @Ans as real
declare @Miles as real

set @DegToRad = 57.29577951
set @Ans = 0
set @Miles = 0

if @lat1 is null or @lat1 = 0 or @long1 is null or @long1 = 0 or @lat2 is
null or @lat2 = 0 or @long2 is null or @long2 = 0
begin
return @Miles 
end
set @Ans = SIN(@lat1 / @DegToRad) * SIN(@lat2 / @DegToRad) + COS(@lat1 / @DegToRad ) * COS( @lat2 / @DegToRad ) * COS(ABS(@long2 - @long1 )/@DegToRad)
set @Miles = 3959 * ATAN(SQRT(1 - SQUARE(@Ans)) / @Ans)
set @Miles = CEILING(@Miles) * 1.609344
return @Miles
END

答案 1 :(得分:0)

避免使用float数据类型,可以使用数字,货币,但由于四舍五入问题,应完全避免使用float。 SQL中的实数,浮点数和双精度数据类型表示近似数值。在您的情况下,您应该使用数字