SQL Server Convert scientific E notation to a decimal value

0vvn1miw  于 2023-10-15  发布在  其他
关注(0)|答案(2)|浏览(91)

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;
disbfnqx

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 unlike decimal , can accept strings in scientific notation. But note that it could introduce accuracy issues:

SELECT TRY_CONVERT(decimal(18,9), TRY_CONVERT(float, MyCol))...

Example . Also see this answer .

yduiuuwa

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:

SELECT TRY_CAST('6E-06' AS DECIMAL(18, 9)) AS OutCol;
SELECT TRY_CAST('-6E-06' AS DECIMAL(18, 9)) AS OutCol;

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 or real first, depending on the possible range of the data.

相关问题