SQL Server 2005 - Format a decimal number with leading zeros (including signed decimals!)

那年仲夏 提交于 2019-12-24 04:44:28

问题


I need to format numbers like:-

1.99
21.34
1797.94
-300.36
-21.99
-2.31

Into a format mask of 0000.00, using SQL-Server 2005 T-SQL. Preserving the signed integers and the decimals after the dot. This would be used for text file exports for a financial system. It requires it to be in this format.

e.g.-

0001.99
0021.34
1794.94
-0300.36
-0021.99
-0002.31

Previously, it was done in MS Access as Format([Total],"0000.00") but SQL-Server doesn't have this function.


回答1:


;WITH t(c) AS
(
SELECT 1.99 UNION ALL 
SELECT 21.34  UNION ALL 
SELECT 1797.94  UNION ALL 
SELECT -300.36  UNION ALL 
SELECT -21.99  UNION ALL 
SELECT -2.31 
)
SELECT  
     CASE WHEN SIGN(c) = 1 THEN '' 
          ELSE '-' 
     END + REPLACE(STR(ABS(c), 7, 2), ' ','0') 
FROM t

Returns

0001.99
0021.34
1797.94
-0300.36
-0021.99
-0002.31



回答2:


You could make a function like this:

CREATE FUNCTION [dbo].padzeros 
(
    @money MONEY,
    @length INT
)
RETURNS varchar(100)
-- =============================================
-- Author:      Dan Andrews
-- Create date: 05/12/11
-- Description: Pad 0's
--
-- =============================================
-- select dbo.padzeros(-2.31,7)
BEGIN

DECLARE @strmoney VARCHAR(100), 
        @result VARCHAR(100)

SET @strmoney = CAST(ABS(@money) AS VARCHAR(100))
SET @result = REPLICATE('0',@length-LEN(@strmoney)) + @strmoney
IF @money < 0 
    SET @result = '-' + RIGHT(@result, LEN(@result)-1)

RETURN @result

END

example:

select dbo.padzeros(-2.31,7)


来源:https://stackoverflow.com/questions/5979204/sql-server-2005-format-a-decimal-number-with-leading-zeros-including-signed-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!