Varchar invalid for sum operator

  • Below doesn't work for varchar column, Any ideas?

    select sum(cast(Enter_your_field_name as int)) from Table_name

    THanks

  • Worked fine in my test. Maybe I'm using a different version. What does this return on your instance?

    CREATE TABLE #Temp (

    AVarcharColumn VARCHAR(20)

    )

    INSERT INTO #Temp

    (AVarcharColumn)

    VALUES ('0')

    GO

    SELECT SUM(CAST(AVarcharColumn AS INT)) FROM #Temp

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • I am running on 2008 SQL Server enterprise. Below is what i am getting

    Msg 8115, Level 16, State 2, Line 1

    Arithmetic overflow error converting expression to data type int.

  • Try this:

    select sum(cast(cast(replace(Enter_your_field_name, ',', '') as decimal(28, 6) as int)) from Table_name

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

  • Admingod (10/29/2015)


    I am running on 2008 SQL Server enterprise. Below is what i am getting

    Msg 8115, Level 16, State 2, Line 1

    Arithmetic overflow error converting expression to data type int.

    You've got values in the string column that are too large to convert to int. Try CAST .. AS BIGINT, or use a DECIMAL that's large enough to hold the values once converted to a numeric type.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • Quick question - Why are you storing numeric values in a string column?

Viewing 6 posts - 1 through 5 (of 5 total)

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