简体   繁体   中英

SQL Query - Converting data type varchar to numeric

I have an issue converting pricing in a SQL query:

CASE CAST(R.Price AS decimal(10,2)) 
   WHEN 'NULL' 
      THEN '0'
END AS 'PricePoint',

Unfortunately, it throws this error:

Error converting data type varchar to numeric.

Thanks for the help.

You are comparing NULL as Varchar so it is giving error.

Use the below query

CASE CAST(R.Price AS decimal(10,2)) WHEN NULL THEN '0'END AS 'PricePoint',

If this is for SQL Server , then you must use this code to use the IS NULL checks (and not the "normal" equality operators):

CASE 
   WHEN CAST(R.Price AS decimal(10, 2)) IS NULL
      THEN '0'
END AS 'PricePoint',

Also: if you want to return a numerical value of 0 , you should again forget about the single quotes around the value - putting it in single quotes is returning a string value (instead of an int ):

CASE 
   WHEN CAST(R.Price AS decimal(10, 2)) IS NULL
      THEN 0
END AS 'PricePoint',

Update: if you want to return the regular prices for anything that is not NULL , add a ELSE clause to your CASE :

CASE 
   WHEN CAST(R.Price AS decimal(10, 2)) IS NULL
      THEN 0
      ELSE CAST(R.Price AS decimal(10, 2)) 
END AS 'PricePoint',

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