How to convert STRING to Decimal in TSQL

Villa 231 Reputation points
2020-12-22T13:54:26.117+00:00

Hello all,
I would like to convert the following field (Answer) string to decimal in TSQL:
Sample string data:
995.00
1,299.00
1,170.00
NA

I have used SELECT CAST(Answer as Decimal) and I received the following error message:
"Error converting data type varchar to numeric."

Thank you in advance for your help.

Developer technologies Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Guoxiong 8,206 Reputation points
    2020-12-22T14:22:29.59+00:00
    DECLARE @T TABLE (
        StringData varchar(20)
    );
    INSERT INTO @T VALUES ('995.00'), ('1,299.00'), ('1,170.00'), (NULL);
    
    SELECT StringData, TRY_CAST(REPLACE(StringData, ',', '') AS decimal(10, 2)) 
    FROM @T;
    

1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 26,586 Reputation points
    2020-12-22T14:04:27.627+00:00

    Just use TRY_CAST() instead of CAST().
    It will produce NULL values when it is impossible to cast into a required data type.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.