mssql convert varchar to float

后端 未结 3 461
北恋
北恋 2020-12-20 12:00

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 mat

相关标签:
3条回答
  • 2020-12-20 12:14

    Use

    Try_convert(float,[Value])
    

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

    0 讨论(0)
  • 2020-12-20 12:15
    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.

    0 讨论(0)
  • 2020-12-20 12:32

    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)
    
    0 讨论(0)
提交回复
热议问题