Error converting data type varchar to float

杀马特。学长 韩版系。学妹 提交于 2021-02-07 20:33:49

问题


Searched and searched on SO and can't figure it out
Tried CASTING each field as FLOAT to no avail, convert didn't get me any further
How can I get the below case clause to return the value stated in the THEN section?

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

section of my SQL query that makes it error:

When cust_trendd_w_costsv.terms_code like '%[%]%' and (prod.dbo.BTYS2012.average_days_pay) - (substring(cust_trendd_w_costsv.terms_code,3,2)) <= 5 THEN prod.dbo.cust_trendd_w_costsv.terms_code

average_days_pay = float
terms_code = char

Cheers!


回答1:


Try to use ISNUMERIC to handle strings which can't be converted:

When cust_trendd_w_costsv.terms_code like '%[%]%' 
and (prod.dbo.BTYS2012.average_days_pay) - 

(case when isnumeric(substring(cust_trendd_w_costsv.terms_code,3,2))=1 
         then cast(substring(cust_trendd_w_costsv.terms_code,3,2) as float)
         else 0
 end)
<= 5 THEN prod.dbo.cust_trendd_w_costsv.terms_code



回答2:


The issue that you're having is that you're specifically searching for strings that contain a % character, and then converting them (implicitly or explicitly) to float.

But strings containing % signs can't be converted to float whilst they still have a % in them. This also produces an error:

select CONVERT(float,'12.5%')

If you're wanting to convert to float, you'll need to remove the % sign first, something like:

CONVERT(float,REPLACE(terms_code,'%',''))

will just eliminate it. I'm not sure if there are any other characters in your terms_code column that may also trip it up.

You also need to be aware that SQL Server can quite aggressively re-order operations and so may attempt the above conversion on other strings in terms_code, even those not containing %. If that's the source of your error, then you need to prevent this aggressive re-ordering. Provided there are no aggregates involved, a CASE expression can usually avoid the worst of the issues - make sure that all strings that you don't want to deal with are eliminated by earlier WHEN clauses before you attempt your conversion




回答3:


If your are sure that Substring Part returns a numeric value, You can Cast The substring(....) to Float :

 .....and (prod.dbo.BTYS2012.average_days_pay) - (CAST(substring(cust_trendd_w_costsv.terms_code,3,2)) as float ) <= 5 ....


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

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