Converting / Casting an nVarChar with Comma Separator to Decimal

后端 未结 4 776
无人共我
无人共我 2020-12-11 17:11

I am supporting an ETL process that transforms flat-file inputs into a SqlServer database table. The code is almost 100% T-SQL and runs inside the DB. I do not own the code

相关标签:
4条回答
  • 2020-12-11 17:35

    This works for me:

    DECLARE @foo NVARCHAR(100)
    SET @foo='12,345.67'
    
    SELECT FLOOR(CAST(REPLACE(@foo,',','') AS DECIMAL(24,10)))
    

    This is probably only valid for collations/culture where the comma is not the decimal separator (ie: Spanish)

    0 讨论(0)
  • 2020-12-11 17:46

    While not necessarily the best approach for my situation, I wanted to leave a potential solution for future use that we uncovered while researching this problem.

    It appears that the SqlServer datatype MONEY can be used as a direct cast for strings with a comma separating the non-decimal portion. So, where SELECT CAST('12,345.56' AS DECIMAL(24,10)) fails, SELECT CAST('12,345.56' AS MONEY) will succeed.

    One caveat is that the MONEY datatype has a precision of 4 decimal places and would require an explicit cast to get it to DECIMAL, should you need it.

    0 讨论(0)
  • SELECT FLOOR (CAST(REPLACE([inputValue], ',', '') AS DECIMAL(24,10)))

    0 讨论(0)
  • 2020-12-11 17:59

    try using REPLACE (Transact-SQL):

    SELECT REPLACE('12,345.67',',','')
    

    OUTPUT:

    12345.67
    

    so it would be:

    SELECT FLOOR( CAST(REPLACE([input value],',','') AS DECIMAL(24,10)))
    
    0 讨论(0)
提交回复
热议问题