How to sum a field that numbers in varchar

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kazantia
    New Member
    • May 2010
    • 2

    #1

    How to sum a field that numbers in varchar

    I want to calculate a sum from a field that has varchar fields, the values are in this format ######,###.
    The numbers before the comma can vary and the ones after the comma are allways 3. I get these values from a table from other database (so modifying that table is no option).

    I know that I can't do a sum on a varchar, so i have to convert it
    i tried different cast and convert statements but i allways get a error that says that the conversion failed

    How can I do this sqlserver itself?
  • Delerna
    Recognized Expert Top Contributor
    • Jan 2008
    • 1134

    #2
    you can't convert it because of the comma.
    You can remove the comma with replace() before converting it

    [code=sql]
    convert( decimal(18,3) , replace( thefieldname , ',' , '' ) )
    [/code]

    Comment

    • Kazantia
      New Member
      • May 2010
      • 2

      #3
      Delerna,
      Thanks for the quick response.
      When i do this i get the number as a integer so the numbers behind the comma are now in front of it.

      How can i solve this?
      I tried to divide by 1000 but stll no numbers behind comma.
      Last edited by Niheel; Jun 1 '10, 11:06 AM. Reason: fixed spelling and punctuation

      Comment

      • Delerna
        Recognized Expert Top Contributor
        • Jan 2008
        • 1134

        #4
        I take it then that the comma is being used to represent a decimal point
        in that case

        replace( thefieldname , ',' , '.' )

        should solve it

        Comment

        Working...