SQL Server 2005 - Format a decimal number with leading zeros (including signed decimals!)
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.
;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
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)
精彩评论