SQL Server: Error converting data type varchar to float

半腔热情 提交于 2019-12-04 06:43:44

问题


I have the following SELECT statement to calculate RADIANS and COS.

SELECT COS(RADIANS(latitude)) as Lat 
FROM tbl_geometry;

But I'm getting an error:

Error converting data type varchar to float.

My attempts:

Attempt #1:

select Cos(convert(float, (Radians(convert(float, latitude))))) as Lat 
from tbl_geometry;

Attempt #2.

select Cos(Radians(convert(float, latitude))) as Lat 
from tbl_geometry;

Both attempts result in the same error.

Note: column Latitude is of type varchar.


回答1:


Use try_convert() to find the invalid data:

select latitude
from tbl_geometry
where try_convert(float, latitude) is null;

try_convert() is available in SQL Server 2012+.




回答2:


You can use:

SELECT      CASE
                WHEN PATINDEX('%[^0-9]%', latitude) > 0 THEN 0
                ELSE Cos(Radians(convert(float,latitude)))
            end as latitude          
FROM        tbl_geometry

You can use the THEN to fill the attribute with null or other values if non-convertable values are encountered. Or you can use the PATINDEX in the WHERE if you want to skip those rows all together. (You may have to play around with the patindex, I don't usually use floats, so I'm not sure what is and isn't allowed. You may want to include decimal points, for example.)



来源:https://stackoverflow.com/questions/41549725/sql-server-error-converting-data-type-varchar-to-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!