简体   繁体   English

SQL查询-将数据类型varchar转换为数值

[英]SQL Query - Converting data type varchar to numeric

I have an issue converting pricing in a SQL query: 我在SQL查询中转换定价时遇到问题:

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. 将数据类型varchar转换为数字时出错。

Thanks for the help. 谢谢您的帮助。

You are comparing NULL as Varchar so it is giving error. 您正在将NULL与Varchar进行比较,因此它给出了错误。

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): 如果这是针对SQL Server的 ,则必须使用以下代码来使用IS NULL检查(而不是“常规”相等运算符):

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 ): 另外:如果要返回数字0 ,则应再次忘记该值周围的单引号-将其放在单引号中将返回字符串值(而不是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 : 更新:如果您想为任何非NULL返回正常价格,请在您的CASE添加一个ELSE子句:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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