converting a blank to numeric

  • I have this query below that runs and just gave me an error msg "Error converting data type varchar to numeric."  The error is due to a blank value in TotalAdj column.  How can I check for blanks and make them 0 on the fly so that the query below does not bomb out on me?

    Select Sum(Cast(amtAdj as Numeric(14,2))) as AmtAdj_Sum, Max(Cast(TotalAdj as Numeric(14,2))) as TotalAdj, count(*) as cnt, InvAdjNum, InvoiceNo, VendorNo, CBRVend 
    INTO [QA_Collection].[dbo].[INVADJ_MAY_JUN_AUG_SEP_OCT_NOV_ALL_Sum]
    FROM [QA_Collection].[dbo].[INVADJ_MAY_JUN_AUG_SEP_OCT_NOV_ALL]
    where rtrim(ltrim(amtadj)) <> ''
    Group by InvAdjNum, InvoiceNo, VendorNo, CBRVend
    Order by InvAdjNum

  • Since you're on SQL 2012, you can use TRY_CAST() instead of just CAST().

    Drew

    J. Drew Allen
    Business Intelligence Analyst
    Philadelphia, PA

  • GrassHopper - Monday, January 29, 2018 12:46 PM

    I have this query below that runs and just gave me an error msg "Error converting data type varchar to numeric."  The error is due to a blank value in TotalAdj column.  How can I check for blanks and make them 0 on the fly so that the query below does not bomb out on me?

    Select Sum(Cast(amtAdj as Numeric(14,2))) as AmtAdj_Sum, Max(Cast(TotalAdj as Numeric(14,2))) as TotalAdj, count(*) as cnt, InvAdjNum, InvoiceNo, VendorNo, CBRVend 
    INTO [QA_Collection].[dbo].[INVADJ_MAY_JUN_AUG_SEP_OCT_NOV_ALL_Sum]
    FROM [QA_Collection].[dbo].[INVADJ_MAY_JUN_AUG_SEP_OCT_NOV_ALL]
    where rtrim(ltrim(amtadj)) <> ''
    Group by InvAdjNum, InvoiceNo, VendorNo, CBRVend
    Order by InvAdjNum

    First question would be why amtAdj and TotalAdj are not a numeric base type to begin with?

    Try a case statement:

    MAX(CAST(case when TotalAdj = '' then '0' else TotalAdj end as Numeric(14,2)))

    __________________________________________________________________________________________________________
    How to Post to get the most: http://www.sqlservercentral.com/articles/Best+Practices/61537/

  • drew.allen - Monday, January 29, 2018 1:21 PM

    Since you're on SQL 2012, you can use TRY_CAST() instead of just CAST().

    Drew

    forgot about the try_cast(), i'm actually in 2016.  Worked, thanks!

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply