Padding Function

Hello all,

Kind of new at this SQL stuff and I'm needing to pad some values when I run a query.  Does anyone know of a good way to pad values in a query via a function or something?  Also I need the pad to be with 0's with my data right justified. (0's on the left)

Thanks,
BBS
LVL 3
thcitAsked:
Who is Participating?
 
rob_lorentzCommented:


replace(str(yourNumber, 8), ' ', '0')

this will create a string 8 chars long left padded with 0s
0
 
adatheladCommented:
e.g.
To pad a value to 4 digits:

DECLARE @intNumber INTEGER
SET @intNumber = 1

SELECT RIGHT('0000' + CAST(@intNumber AS VARCHAR), 4)
0
 
Brian CroweDatabase AdministratorCommented:
CREATE FUNCTION PadLeft(@text varchar(1000), @fillchar char(1), @totallength int)
RETURNS varchar(1000)
AS
WHILE LEN(@text) < @totallength
     SET @text = @fillchar + @text
RETURN @text
END
0
 
thcitAuthor Commented:
Thanks Rob, that was exactly what I needed.  Functional and lightweight.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.