从nvarchar到数字的转换失败

时间:2016-10-19 06:40:06

标签: sql tsql

我正在尝试执行此查询,但发生以下错误:

Error converting data type nvarchar to numeric

这是我的疑问:

Select Top 20 *,dbo.GetDistance(35.5,33.8, Longitude, Latitude) as Distance 
From ViewBranchCoordinates
order by Distance desc

如果我删除此行order by Distance desc,则查询正常运行且没有错误

这是函数GetDistance

ALTER FUNCTION [dbo].[GetDistance] 
(
-- Add the parameters for the function here
  @Long decimal(30,24), @Lat decimal(30,24), @Long2 decimal(30,24), @Lat2   decimal(30,24)
)
--decimal(8,6), @Long)
RETURNS decimal(38,28)
AS
BEGIN
-- Declare the return variable here
DECLARE @Distance decimal(38,28)
DECLARE @valueOne decimal(30,24)
DECLARE @valueTwo decimal(30,24)
DECLARE @dLat decimal(30,24)
DECLARE @dLng decimal(30,24)
DECLARE @SectionOne decimal(30,24)
DECLARE @SectionTwo decimal(30,24)

Select @dLat = RADIANS(@Lat - @Lat2)
Select @dLng = RADIANS(@Long -  @Long2)
Select @SectionOne = square(sin((@dLat)/2))
Select @SectionTwo = cos(RADIANS(@Lat)) *  cos(RADIANS(@Lat2)) * square(sin(@dLng / 2))
Select @valueOne =CONVERT(decimal(30,24),@SectionOne + @SectionTwo) 
Select @valueTwo = 2 * ATN2(SQRT(@valueOne), SQRT(1 - @valueOne))
Select @Distance = 6371000 * @valueTwo

RETURN @Distance

END

请帮助

1 个答案:

答案 0 :(得分:0)

我认为这也会失败?

 Select Top 20 *
 ,dbo.GetDistance(35.5,33.8, cast (Longitude as decimal (30,24)), cast(Latitude as (30,24)) as Distance 
 From ViewBranchCoordinates

您的函数需要某种类型的数据。如果您的lat / long列是nvarchar,则非数字数据可以在这些列中。

搜索问题数据,例如

Select *
From ViewBranchCoordinates
Where try_cast (longitude as numeric) IS NULL

然后你需要修复数据。

相关问题