Search code examples
sql-serversqldatatypes

Storing a number with commas and periods in sql server (data type)


What is the best way to store a number in SQL SERVER so that if i have a number like...

192,234.35

It will get stored as such?

Will Numeric as DataType do the trick?


Solution

  • Don't store numerical data as text. I prefer decimal but anything is almost better than text. Here's a simple idea to consider.

    declare @someDecimal decimal (8,2) = 192234.35
    declare @someText varchar(16) = '192,234.35'
    
    --here's how you would have to compare your text to an actual number
    select 'True' where @someDecimal = convert(decimal(8,2),replace(@someText,',',''))
    
    --then if you wanted to do any math on it, you would also have to convert it.
    select convert(decimal(8,2),replace(@someText,',','')) * 2
    --versus just
    select @someDecimal * 2
    
    --If you want to display it, use format...
    select FORMAT(@someDecimal,'#,0.0000')
    

    Ordering your data is where you would find big problems since it's done character by character. Again, this is why you don't store it as text.

    declare @tableOfText table (d varchar(16))
    insert into @tableOfText (d)
    values
    ('001'),
    ('010'),
    ('10'),
    ('110'),
    ('011'),
    ('1'),
    ('12')
    
    select * from @tableOfText order by d desc