2014-04-10 89 views
0

我有兩個字段保存數據爲varchar轉換VARCHAR到十進制

字段1 = 10,000.00和Field2 = 5,000.00

我現在需要添加這兩個領域找到總和。但是,當我添加爲字段1 +字段2的

結果是10,000.005,000.oo

我試圖用CAST(字段1爲十進制(12,2)),但它拋出一個錯誤,它不能將varchar轉換爲數字。

幫我一把。

     SELECT  [1] AS ContractPriceExcluded, [2] AS Anticipated, [3] AS Approved, [4] AS claims, [5] AS ProvisionalSums, [6] AS CommitmentsToDate, [7] AS AnticipatedFCost, 
        [8] AS VarianceToContract, [9] AS CertifiedPayments,[10] AS ContractPriceIncluded , [11] AS ProvisionalSumsNotactivated ,description, status, ReferenceNo 
        FROM   (SELECT  ISNULL([Workflow_CustomFormfields].[fieldnumber], '') AS fieldnumber, 
             CAST(REPLACE([Workflow_CustomFormFields].fieldvalue,',','')as Decimal(12,2)) AS fieldvalue, isnull(workflow_customforms.subject, '') AS description, 
              isnull(workflow_customforms.categoryvalue, '') AS status, isnull(workflow_customforms.reference, '') AS ReferenceNo 
        FROM   [dbo].[Workflow_CustomFormfields] INNER JOIN 
              dbo.Workflow_CustomForms ON [dbo].[Workflow_CustomForms].[Id] = dbo.Workflow_CustomFormfields.customformId 
        WHERE  dbo.Workflow_CustomForms.ProjectId = 1 AND dbo.Workflow_CustomForms.CustomformtypeId = 75) PS PIVOT (max(fieldvalue) FOR fieldnumber IN ([1], [2], 
        [3], [4], [5], [6], [7], [8], [9],[10],[11])) AS pivot_fieldvalue 
+3

爲什麼不把它作爲小數保存在第一位呢? –

回答

4
select cast(replace('10,000.00',',','') as decimal(12,2)) 

的問題是逗號

+0

是的,你是對的!逗號是問題。 –

+0

嗨,這個解決方案工作正常。但是,當我在case語句中使用它時,它會引發同樣的錯誤。請查看下面的case語句。 – user3383390

+0

(CASE WHEN [workflow_customformfields] .FieldType = '日期' THEN dbo.CustomForm_GetDate(workflow_customformfields.fieldvalue) \t \t \t \t \t \t \t \t \t \t \t WHEN [workflow_customformfields] .FieldType = '雙' THEN \t \t \t \t \t \t \t \t \t \t \t CAST(REPLACE(Workflow_CustomFormFields.fieldvalue, '', '')作爲十進制(12,2)) \t \t \t \t \t \t \t \t \t \t \t ELSE ISNULL(workflow_customformfields.fieldvalue, '')END)AS fieldValue方法 – user3383390

0

你鑄造兩個數值爲十進制?這工作正常

DECLARE @one varchar(8), @two varchar(8) 
SET @one = '10,000.00' 
SET @two = '5,000.00' 
SELECT CAST(replace(@one,',','') AS decimal(12,2))+ 
     CAST(replace(@two,',','') AS decimal(12,2)) 
+0

請仔細看看問題。 – AK47

+0

看了。編輯迴應 – Raj

0

您必須刪除逗號並轉換爲十進制。見下文。

declare @field1 varchar(50) = '10,000.00' , 
@field2 varchar(50)= '5,000.00' 

select Convert(decimal(10,2),replace(@field1,',','')) +Convert(decimal(10,2),replace(@field2,',',''))