SQL Server format decimal places with commas

后端 未结 5 1157
天涯浪人
天涯浪人 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:18

    without considering this to be a good idea...

    select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))
    

    Function

    -- Author:      bummi
    -- Create date: 20121106
    CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50)) 
    RETURNS Varchar(50)
    AS
    BEGIN
    declare @OutStr varchar(50)
    declare @i int
    declare @run int
    
    Select @i=CHARINDEX('.',@NumStr)
    if @i=0 
        begin
        set @i=LEN(@NumStr)
        Set @Outstr=''
        end
    else
        begin   
         Set @Outstr=SUBSTRING(@NUmStr,@i,50)
         Set @i=@i -1
        end 
    
    
    Set @run=0
    
    While @i>0
        begin
          if @Run=3
            begin
              Set @Outstr=','+@Outstr
              Set @run=0
            end
          Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr  
          Set @i=@i-1
          Set @run=@run + 1     
        end
    
        RETURN @OutStr
    
    END
    GO
    

提交回复
热议问题