简体   繁体   中英

Failed Convert Varchar to a Float

I have a table that has got a mixture of data, its of type Varchar but i has got numbers and a few strings in it which are Building and IBS . However i'm trying to get rid of the strings. I only know how to get rid of one. When i try to add another, It complains about arguments, how can i do it.

ROUND( ISNULL( CASE 
                  WHEN [lentgth] IN( 'Building', '', 'IBS', '') THEN 0 
                  ELSE CONVERT(FLOAT, REPLACE([lentgth], 'm', 'i')) 
               END, 0 ), 0 )

You can use isnumeric function:

ROUND(cast(case
            when isnumeric(lentgth) = 0 then 0 
            else lentgth
           end as float)
     , 0)

In SQL Server 2012+, you can use TRY_CONVERT() :

TRY_CONVERT(FLOAT, REPLACE([lentgth], 'm', 'i'))

This returns NULL if the conversion cannot be done. If you want 0 , use COALESCE() or IFNULL() :

ISNULL(TRY_CONVERT(FLOAT, REPLACE([lentgth], 'm', 'i')), 0)

COALECE() evaluates the first argument twice (which I consider to be an MS SQL performance bug). For that reason, ISNULL() is preferable when the first argument is a function all or subquery.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM