What is the best practice for right-justifying a numeric in TSQL?
I have to format a fixed length extract file and need to have the Numeric fields right justified. (I am using SQL Server 2005)
I found this, which seems pretty straight forward.
right(' '+convert(varchar(20),a.num),12)
Here is the full Select statement
select a.num, fixed_number = right(' '+convert(varchar(20),a.num),12) from ( --Test Data select num = 2400.00 union all select num = 385.00 union all select num = 123454.34 ) a Results: num fixed_number ---------- ------------ 2400.00 2400.00 385.00 385.00 123454.34 123454.34 (3 row(s) affected)
I am asking this question because I found this line of code at work, which appears INSANELY complex (It is also removing the decimal and zero filling)
CAST(REPLACE(REPLICATE('0', 12 - LEN(REPLACE(CAST(CONVERT(DECIMAL(10,2),@DD8DBAMT) AS VARCHAR),'.',''))) + CAST(CONVERT(DECIMAL(10,2),@DD8DBAMT) AS VARCHAR),'.','') AS VARCHAR(12))
Updated:
Daniel Pratt’s idea of using a function got me looking at SQL# (which we own). It has a function called PadLeft, which surprisingly enough had the same parameters and functionality as Daniel Pratt’s fn_PadRight function defined in his answer below.
Here is how to use SQL# function:
DECLARE @F6D2 AS DECIMAL(8,2) SET @F6D2 = 0 SQL#.String_PadLeft(@F6D2,9,' ') SQL#.String_PadLeft(123.400,9,' ') SQL#.String_PadLeft('abc',9,' ')
It can take both numbers and strings.
The only thing I can suggest to help with the ‘insane complexity’ is to encapsulate it in one or more functions. Here’s a somewhat modified version of something we’re using: