操作数类型冲突地理与浮点数不兼容

Operand type clash geography is incompatible with float

我想弄清楚如何构建一个函数,使用经度和纬度来测量从一个位置到另一个位置的距离(以英里为单位)。当 EXECUTE 为 运行 时,将添加参数。我正在尝试使用 "geography::Point()" 和 "STDistance" 而不是浮点数来做到这一点。

IF OBJECT_ID('dbo.udfDistanceMiles') IS NOT NULL
  DROP FUNCTION dbo.udfDistanceMiles
GO
CREATE FUNCTION dbo.udfDistanceMiles 
(
    @long1 geography,
    @long2 geography,
    @lat1 geography,
    @lat2 geography
)
RETURNS geography
AS
BEGIN
    DECLARE @from geography
    DECLARE @to geography
    DECLARE @kilo geography
    DECLARE @miles as geography

    SET @from = geography::Point(@lat1,@long1,4268);
    SET @to = geography::Point(@lat2,@long2,4268);
    SET @kilo = (SELECT @from.STDistance(@to));
        BEGIN
            SET @miles = (@kilo * '.621371');
        END 

    RETURN @miles

END
GO

这是一项 class 我正在处理空间数据库的作业,但我 运行 遇到了一个我无法弄清楚的障碍。我 运行 在尝试创建函数时遇到了这个操作数类型冲突:

Msg 206, Level 16, State 2, Procedure udfDistanceMiles, Line 19
Operand type clash: geography is incompatible with float
Msg 206, Level 16, State 2, Procedure udfDistanceMiles, Line 19
Operand type clash: geography is incompatible with float
Msg 206, Level 16, State 2, Procedure udfDistanceMiles, Line 20
Operand type clash: geography is incompatible with float
Msg 206, Level 16, State 2, Procedure udfDistanceMiles, Line 20
Operand type clash: geography is incompatible with float
Msg 206, Level 16, State 2, Procedure udfDistanceMiles, Line 21
Operand type clash: float is incompatible with geography
Msg 403, Level 16, State 1, Procedure udfDistanceMiles, Line 23
Invalid operator for data type. Operator equals multiply, type equals geography.

任何对新手的帮助将不胜感激。

谢谢

约翰

您函数的参数输入似乎有误。也就是说,如果您要传递 lat/long 对,则它们是 float 类型,而不是 geography 类型。您也许可以只改变这些,让其他一切都解决。

这是对我有用的完成函数,以及它的 EXEC,用于测量从犹他州 SLC 到加利福尼亚州洛杉矶的英里数。

ALTER FUNCTION [dbo].[udfDistanceMiles] 
(
    @long1 float,
    @long2 float,
    @lat1 float,
    @lat2 float
)
RETURNS float
AS
BEGIN
    DECLARE @from geography
    DECLARE @to geography
    DECLARE @miles as float

    SET @from = geography::Point(@lat1,@long1,4326);
    SET @to = geography::Point(@lat2,@long2,4326);
    SET @miles = (SELECT ((@from.STDistance(@to) * '.001') * '.621371'));
    --SET @miles = (SELECT (@from.STDistance(@to) * '.621371'));

    RETURN @miles

END

执行官:

USE DBM384;
GO

DECLARE @miles float= NULL;

EXEC @miles = dbo.udfDistanceMiles @lat1= 34, @long1= -118, @lat2= 40.758701, @long2= -111.876183;

PRINT @miles;