Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert varchar to float IF ISNUMERIC

I have a column that contains characters and numbers

12
13
14
19K/YR
22

So the column type is varchar. But then I'm also doing some computations with this column, so I'm trying to convert the data to float if it is numeric.

This gives me an error though:

SELECT CASE ISNUMERIC(QTY) 
         WHEN 1 THEN CAST(QTY AS float) 
         ELSE QTY 
       END AS test
like image 912
Pod Mays Avatar asked May 23 '11 03:05

Pod Mays


People also ask

Can you convert varchar to float?

If you are planning to convert varchar to float you should know that these two data types are not compatible with each other.

Can we use varchar for numeric in SQL?

As the name suggests, varchar means character data that is varying. Also known as Variable Character, it is an indeterminate length string data type. It can hold numbers, letters and special characters.


1 Answers

You can't cast to float and keep the string in the same column. You can do like this to get null when isnumeric returns 0.

SELECT CASE ISNUMERIC(QTY) WHEN 1 THEN CAST(QTY AS float) ELSE null END
like image 100
Mikael Eriksson Avatar answered Oct 06 '22 22:10

Mikael Eriksson