mssql convert varchar to float

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I have a field value productlength of 0.123. This is from a view and has a data type of varchar.

I need to convert it to a float or numeric value so as o perform math comparisons.

convert(float,productlength) and cast(productlength as float) both do not work.

error varchar cant be converted to float or somethiing liek that.

From what I have read varchar can simply not be converted to a numeric string?

Any clever ways around this?

回答1:

You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:

declare @thing varchar(100)  select @thing = '122.332'  --This returns 1 since it is numeric. select isnumeric(@thing)  --This converts just fine. select convert(float,@thing)  select @thing = '122.332.'  --This returns 0 since it is not numeric. select isnumeric(@thing)  --This convert throws. select convert(float,@thing) 


回答2:

Use

Try_convert(float,[Value]) 

See https://raresql.com/2013/04/26/sql-server-how-to-convert-varchar-to-float/



回答3:

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x'; select CONVERT(float, @INPUT) YOUR_QUERY , case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED 

above will return values

however below query wont work

DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x'; select CONVERT(float, @INPUT) YOUR_QUERY , case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED 

as @INPUT_1 actually has varchar in it.

So your output column must have a varchar in it.



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