5

I have a column of varchar datatype populated with a mix of values such as 1.2, 5.33 while also having NULLs and EMPTY strings. I want to convert all the values to decimal while treating NULLs and EMPTY strings as 0.

I can change the NULLs or EMPTY strings using the CONVERT function like below. Like this I replace the NULLs and EMPTY strings with a varhcar 0.

CASE WHEN Column1 = '' OR Column1= NULL THEN '0' ELSE Column1 END AS 'NewColumn1'

However what I want to do is to be able to then convert this data (output of NewColumn1) into decimal but when I place the CASE expression into a CONVERT or a CAST function I will have errors.

I also tried the following. CONVERT(DECIMAL(10,4), ISNULL(Column1, '0')) however it fails since here I am not handling the EMPTY strings.

Any ideas how can I solve this problem.

2
  • 2
    ... OR Column1 IS NULL ... Commented Apr 4, 2017 at 7:39
  • CAST((CASE WHEN Column1='' OR Column1 IS NULL THEN '0' ELSE Column1 END ) AS DECIMAL(18,2)) Commented Apr 4, 2017 at 7:41

4 Answers 4

8

Simple way:

SELECT CONVERT(DECIMAL(10, 4), ISNULL(NULLIF(Column1, ''), '0'))

Your CASE expression doesn't work because you're checking if Column1 = NULL. You should check if it IS NULL.

CASE WHEN Column1 = '' OR Column1 IS NULL THEN '0' ELSE Column1 END AS 'NewColumn1'
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Marko. This first solution is working and also very clean.
@user2307236 if this answer solved your issue you have to accept it, it is not sufficient to say thanks. Also When having many well answered question without accepting good answers. Other user will not pay attention for your questions. good luck
3

Try this,

SELECT CAST(ISNULL(NULLIF(Column1, ''),0) AS DECIMAL(12,2)) FROM table

2 Comments

This doesn't work as required - it doesn't work for empty string.
I fixed that issue
0

Try this:

SELECT CAST(COALESCE(NULLIF(Column1, ''),'0') AS DECIMAL(14,5)) AS Column1 
FROM table

Comments

0

We can first convert varchar or char into INT and then decimal. It will handle both null and empty string. Ex. CONVERT(Decimal(precision, scale), convert(INT, Column))

1 Comment

this looks like it will truncate decimal values (e.g. 1.2 would become 1.0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.