[英]Convert Text or Varchar to Decimal type
在[Return rate]
欄中,我的值如下:
20.0%
17.1%
etc
在查詢中,我想在計算中使用此值。
因此,首先,我用一個空字符串''
替換'%'
''
:
REPLACE([Return Rate], '%' ,'') AS [Test]
這有效,當[返回率]為'20 .0%'時,我得到的值類似於'20 .0'。
然后,我嘗試在計算中使用此[Test]值,例如:
(REPLACE([Return Rate], '%' ,'') * 10) AS [Test]
但是我從邏輯上獲得了一個錯誤,因此我嘗試轉換此文本值來執行我的計算:
CAST ( REPLACE([Current Xelus FE Return Rate], '%' ,'') AS decimal(2,1)) [Decimal Test]
在這里,我得到了錯誤:
Arithmetic overflow error converting varchar to data type numeric. Warning: Null value is eliminated by an aggregate or other SET operation.
有沒有人回答這個錯誤? 非常感謝,
如果您的任何行包含空值,您將收到此錯誤。 嘗試使用IsNull,如下所示:
CAST(
IsNull(
REPLACE([Current Xelus FE Return Rate], '%' ,'')
, '0.0')
AS decimal(5,1)) [Decimal Test]
如果您的數據包含非數字值(如您所述,類似“ 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]
嘗試將其轉換為FLOAT-十進制(2,1)是不夠的:
CAST ( REPLACE([Current Xelus FE Return Rate], '%' ,'') AS FLOAT)
然后您應該可以進行進一步的計算
CAST ( REPLACE([Current Xelus FE Return Rate], '%' ,'') AS FLOAT) * 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.