纬度和经度转换错误

时间:2013-02-27 16:04:30

标签: sql sql-server tsql

我正在尝试在我的数据库中执行特定查询,但发生以下错误

表San_Filial

Filial_Id   Name    lat            lon
2           A       -19.926131     -43.924373
3           B       -19.952192     -43.938789
4           C       -19.939626     -43.924541
5           D       -19.95529      -43.92953
6           E       -19.9099       -43.93124
7           F       -19.926191     -43.946067
9           G       -19.97125      -43.96622
14          H       -19.89038      -43.921734
17          I       -19.88838      -43.93059
19          J       -19.94305      -43.94093

查询

SELECT *
FROM San_Filial 
WHERE San_Filial.Credenciada_Id IN (2,3,4,5,6,7,9,14,17)
AND ACOS(COS(RADIANS(ltrim(San_Filial.lat))) 
* COS(RADIANS(convert(float, -19.926131))) 
* COS(RADIANS(ltrim(San_Filial.lon)) 
- RADIANS(convert(float, -43.924373))) 
+ SIN(RADIANS(ltrim(San_Filial.lat))) 
* SIN(RADIANS(convert(float, -19.926131)))) * 6380 < 5.0 

错误

Mesage 8114, Level 16, State 5, Line 1
Error converting data type varchar to float.

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

首先查看您是否有任何格式不正确的数据:

select *
from san_filia1
wHERE San_Filial.Credenciada_Id IN (2,3,4,5,6,7,9,14,17) and
      (isnumeric(lat) = 0 or isnumeric(long) = 0)

从这里,您将看到导致问题的原因,然后您可以解决它。

正确的解决方案可能就是这样:

select *
from (select sf.*,
             (case when isnumeric(lat) then cast(lat as float) end) as latf,
             (case when isnumeric(long) then cast(long as float) end) as longf
      from san_filial sf
     ) sf
where . . . -- use Latf and Longf instead of lat and long

您需要在case语句中进行转换,以确保它按预期工作。 SQL不保证语句的排序,并且可以在计算之后应用过滤器。