What is the best practice for lawfully substantiating a number in TSQL?
I need to format a fixed-length extent file and I need the Numeric fields to be correctly justified. (I am using SQL Server 2005)
I found this one that seems pretty straight forward.
right(' '+convert(varchar(20),a.num),12)
Here is the complete Select statement
select a.num, fixed_number = right(' '+convert(varchar(20),a.num),12) from (
I ask this question because I found this line of code in a job that appears DIRECTLY complex (it also removes the decimal and zero padding)
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, the idea of using a function made me look at SQL # (which we have). It has a function called PadLeft , which, oddly enough, had the same parameters and functionality as the Daniel Pratt function fn_PadRight defined in his answer below.
Here's how to use the SQL # function:
DECLARE @F6D2 AS DECIMAL(8,2) SET @F6D2 = 0 SQL
It can accept both numbers and strings.