I'm using SQL Server 2019 and have a column with decimal values but sometimes source sends data with scientific E notation. I tried the below query to convert with a value specified and that works as expected.
SELECT TRY_CAST(6E-06 AS DECIMAL(18, 9)) AS OutCol;
SELECT TRY_CAST(-6E-06 AS DECIMAL(18, 9)) AS OutCol;
Output:
0.000006000
-0.000006000
But, when I use it with my table its unable to convert. I get NULL
. MyCol
is of nvarchar
datatype.
SELECT TRY_CAST(MyCol AS DECIMAL(18, 9)) AS OutCol
FROM Test;
2条答案
按热度按时间disbfnqx1#
You should probably fix that so you're not storing numeric values in string columns. We have numeric types precisely so we can avoid this kind of problem.
Anyway,
float
is a little more forgiving, and unlikedecimal
, can accept strings in scientific notation. But note that it could introduce accuracy issues:Example . Also see this answer .
yduiuuwa2#
The
6E-06
and-6E-06
in the question example are already binary literals. You'll get same results in your test if you run it like this:Unfortunately, SQL Server doesn't have built-in support for directly converting to numeric or decimal types from strings formatted in scientific notation. Therefore your best option is probably pre-processing this data. Failing that, you're left with some rather complex code. , but you might be able to simplify things by converting to a
float
orreal
first, depending on the possible range of the data.