SQL 2012错误的ACOS功能

时间:2012-04-17 09:40:37

标签: sql-server sql-server-2012

我在SQL Server 2012 ACOS功能中遇到了这个错误:

declare @lat1 decimal(12,10), @lon1 decimal(12,10), @lat2 decimal(12,10), @lon2 decimal(12,10)
declare @dist float

select @lat1=51.1790825000, @lon1= 4.1590020000, @lat2= 51.1790825000, @lon2= 4.1590020000  
set @dist = SIN(RADIANS(@lat1)) * SIN(RADIANS(@lat2)) + COS(RADIANS(@lat1)) * COS(RADIANS(@lat2)) * COS(RADIANS(@lon1 - @lon2))

print @dist
print ACOS(1)
print ACOS(@dist)

最后一个打印功能给出“发生了无效的浮点运算”。这在SQL Server 2008中运行良好

维拉德

4 个答案:

答案 0 :(得分:3)

看起来你正试图计算地球上两点之间的距离。让您的生活更轻松,并使用内置的地理类型。

DECLARE @lat1 DECIMAL(12, 10) ,
    @lon1 DECIMAL(12, 10) ,
    @lat2 DECIMAL(12, 10) ,
    @lon2 DECIMAL(12, 10)
DECLARE @dist FLOAT

SELECT  @lat1 = 51.1790825000 ,
        @lon1 = 4.1590020000 ,
        @lat2 = 51.1790825000 ,
        @lon2 = 4.1590020000

DECLARE @p1 GEOGRAPHY = GEOGRAPHY::Point(@lat1, @lon1, 4326) ,
    @p2 GEOGRAPHY = GEOGRAPHY::Point(@lat2, @lon2, 4326)

SELECT  @dist = @p1.STDistance(@p2)

答案 1 :(得分:1)

使用

print ACOS(CASE WHEN @dist > 1 THEN 1 ELSE @dist END)

@dist是一种float数据类型,由于四舍五入问题,实际上略高于1,如下所示。

SELECT CAST(@dist AS BINARY(8)) AS [@dist], 
       CAST(CAST(1 AS FLOAT) AS BINARY(8)) AS [1]

返回

@dist              1
------------------ ------------------
0x010000000000F03F 0x000000000000F03F

010000000000F03F插入the IEEE converter here表示此约为1.0000000000000002220446049250313080847263,可从下方验证(返回Y

SELECT 
     CASE WHEN @dist between 1.0000000000000002220446049250313080847 AND 
                             1.0000000000000002220446049250313080848 
     THEN 'Y' ELSE 'N' END

答案 2 :(得分:1)

acos()函数的浮点值参数必须介于-1到1之间。因此

FUNCTION [dbo].[Calculate_Distance]  
(  
@Lat1 float, @Long1 float, @Lat2 float, @Long2 float  
)  
RETURNS float  
AS  
BEGIN  

    DECLARE @acosValue float     
    DECLARE @R float  
    SET @R = 3958.7558657440545 -- mi       
    DECLARE @Distance float  
    Set @acosValue= cos( radians(@Lat1) ) * cos( radians( @Lat2 ) ) * cos( radians( @Long2 ) - radians(@Long1) ) + sin( radians(@Lat1) ) * sin( radians( @Lat2 ) ) ;
    IF @acosValue>1.0 
    Begin
    Set @acosValue=1.0;
     End
    IF @acosValue<-1.0 
    Begin
    Set @acosValue=-1.0;
     End

    SET @Distance = acos(@acosValue)
     * @R;  

    RETURN @Distance  

END 
GO

试试这个

答案 3 :(得分:0)

正如其他答案所述,您有一个浮点问题,根据不同的CPU架构会出现不同的问题。但是,有一个简单的单线程可以解决您的问题:

declare @dist float需要更改为declare @dist decimal(12, 10)