简体   繁体   English

将文本或Varchar转换为十进制类型

[英]Convert Text or Varchar to Decimal type

In the column [Return rate] , I have values like : [Return rate]栏中,我的值如下:

20.0%
17.1% 
etc

In my query, I want to use this values in a calculation. 在查询中,我想在计算中使用此值。

So first, I replace the '%' by an empty string '' : 因此,首先,我用一个空字符串''替换'%' ''

REPLACE([Return Rate], '%' ,'') AS [Test]

This works, and I get values like '20.0' when [Return rate] was '20.0%'. 这有效,当[返回率]为'20 .0%'时,我得到的值类似于'20 .0'。

Then I try to use this [Test] value in a calculation, for instance: 然后,我尝试在计算中使用此[Test]值,例如:

(REPLACE([Return Rate], '%' ,'') * 10) AS [Test]

But I logically obtain an error, so I try to convert this text value to perform my calculation: 但是我从逻辑上获得了一个错误,因此我尝试转换此文本值来执行我的计算:

CAST ( REPLACE([Current Xelus FE Return Rate], '%' ,'') AS decimal(2,1))  [Decimal Test]

And it's here that I get the error: 在这里,我得到了错误:

 Arithmetic overflow error converting varchar to data type numeric. Warning: Null value is eliminated by an aggregate or other SET operation. 

Has someone the answer to this error? 有没有人回答这个错误? Thanks a lot, 非常感谢,

If any of your rows contain null values, you will get this error. 如果您的任何行包含空值,您将收到此错误。 Try an IsNull, like this: 尝试使用IsNull,如下所示:

CAST( 
 IsNull( 
  REPLACE([Current Xelus FE Return Rate], '%' ,'') 
 , '0.0')
AS decimal(5,1))  [Decimal Test]

If your data contains non-numeric values (as you mentioned, values like 'N/A'), you can elimimate them with the IsNumeric() function: 如果您的数据包含非数字值(如您所述,类似“ N / A”的值),则可以使用IsNumeric()函数消除它们:

CAST( 
  CASE WHEN IsNumeric(
    IsNull( 
      REPLACE([Current Xelus FE Return Rate], '%' ,'') 
    , '0.0')
  ) = 1 THEN IsNull(REPLACE([Current Xelus FE Return Rate], '%' ,''),'0.0')
  ELSE '0.0' 
  END
AS decimal(5,1))  [Decimal Test]

Try casting it to FLOAT - decimal(2,1) is not enough: 尝试将其转换为FLOAT-十进制(2,1)是不够的:

CAST ( REPLACE([Current Xelus FE Return Rate], '%' ,'') AS FLOAT)

Then you should be able to do further calculations 然后您应该可以进行进一步的计算

CAST ( REPLACE([Current Xelus FE Return Rate], '%' ,'') AS FLOAT) * 10

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

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