简体   繁体   中英

How to convert a varchar to decimal in a SQL Server query?

In my database I gave CHARGECODE and CHARGECODE_URGENT columns with a varchar datatype and length 15.

However to nap I need that two data become decimals.

Most values ​​are for example (40 or 55). But there are also 44.00 and -450.

So I tried to convert them with CAST and CONVERT.

string cmdText = @"SELECT SUM(CASE WHEN TEST_URGENT = 'T' THEN CAST(CHARGECODE_URGENT AS decimal) ELSE CAST(CHARGECODE AS decimal) END) AS Somme FROM  JOB_HEADER";

I also tried:

 string cmdText = @"SELECT SUM(CASE WHEN TEST_URGENT = 'T' THEN CONVERT(decimal, CHARGECODE_URGENT) ELSE CONVERT(decimal,CHARGECODE) END) AS Somme FROM  JOB_HEADER";

I still get this error :

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: Error converting data type varchar to numeric.

Yet I check if the conversion is possible and it seems so. So I think I have a syntax problem. Thanks for your help

Use TRY_CAST() or TRY_CONVERT() :

SELECT SUM(CASE WHEN TEST_URGENT = 'T'
                THEN TRY_CAST(CHARGECODE_URGENT AS decimal)
                ELSE TRY_CAST(CHARGECODE AS decimal)
           END) AS Somme
FROM JOB_HEADER;

To find the bad values, you can do:

select CHARGECODE_URGENT
from job_header
where try_cast(CHARGECODE_URGENT as decimal) is null and
      test_urgent = 'T';

and:

select CHARGECODE
from job_header
where try_cast(CHARGECODE as decimal) is null and
      test_urgent <> 'T';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM