4,707 questions
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;
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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.
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;
Just use TRY_CAST() instead of CAST().
It will produce NULL values when it is impossible to cast into a required data type.