SQL Server format decimal places with commas

后端 未结 5 1145
天涯浪人
天涯浪人 2020-12-10 03:43

How can I convert the decimal values to have some commas?

this Helps me. But my problem the decimal places are set to 2 only..I want the decimal to be 2, 3, or 4..ex

5条回答
  •  暖寄归人
    2020-12-10 04:13

    Thankfully(?), in SQL Server 2012+, you can now use FORMAT() to achieve this:

    FORMAT(@s,'#,0.0000')
    


    In prior versions, at the risk of looking real ugly

    [Query]:

    declare @s decimal(18,10);
    set @s = 1234.1234567;
    select replace(convert(varchar,cast(floor(@s) as money),1),'.00',
        '.'+right(cast(@s * 10000 +10000.5 as int),4))
    

    In the first part, we use MONEY->VARCHAR to produce the commas, but FLOOR() is used to ensure the decimals go to .00. This is easily identifiable and replaced with the 4 digits after the decimal place using a mixture of shifting (*10000) and CAST as INT (truncation) to derive the digits.

    [Results]:

    |   COLUMN_0 |
    --------------
    | 1,234.1235 |
    

    But unless you have to deliver business reports using SQL Server Management Studio or SQLCMD, this is NEVER the correct solution, even if it can be done. Any front-end or reporting environment has proper functions to handle display formatting.

提交回复
热议问题