Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert varchar to flaot with multiple CASE – SQL

I have a dataset with number (some negative) as varchar in my column, some cell also contain ‘#N/A’, ‘#DIV/0!’ and ‘Null’. I’m trying to convert it to float.

But when I run my code it convert everything to ‘Null’

Here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Select col1,
case 
    when col1 = '#DIV/0!' then null 
    when col1 = '#N/A' then null
    else TRY_CAST ( col1 as float)
end as col2
from test

And a dataset sample:

CREATE or replace table Test (
  Col1 VARCHAR(30));
  
INSERT INTO silver_db.public.test
    (Col1)
VALUES 

    ('#DIV/0!'),
    ('#N/A'),
    ('5 554 548'),
    ('-230 896'),
    ('Null');

>Solution :

It will not know what to do with the numbers with spaces in it. You need to replace these:

Select col1,
case 
    when col1 = '#DIV/0!' then null 
    when col1 = '#N/A' then null
    else TRY_CAST(REPLACE(col1, ' ' ,'') as float)
end as col2
from test
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading