I have been dependent on the pad functions since the clipper days as it helped alot on formatting fixed length ids(invoice no., receipt no., etc.) Although I think the only purpose of formatting a number to fixed length precedeed by (usually) a zero is that it looks good on reports(i.e. 1234 -> 001234), aside from that it constraints the number to the fixed length.
So it's sort of disappointing that Sql Server(at least 2K) doesn't have a function for character padding, and have to resort to writing my own function in T-Sql. I have taken advantage of the default behavior of the STR() w/c right justifies a float expression by padding it with spaces and issue a REPLACE() to replace with our pad character. So instead of my usual:
[code language="T-SQL"]
SET @Delta = LEN(@NumToPad) - @FixedLength
SELECT @NumToPad + CAST(REPLICATE(@PadChar,@Delta) AS NVARCHAR(4000))
[/code]
where the @Delta is the actual length minus the fixed length.
Taking advantage of STR() I can do it like so:
[code language="T-SQL"]
SELECT REPLACE(STR(@NumToPad, @FixedLength), SPACE(1), @PadChar)
[/code]
Quick and dirty routine. Some things to note though:
a.) if the number to pad is greater than the fixed length, STR() will truncate it(num to pad) to asterisk(*)
b.) Using REPLICATE() is faster than REPLACE() as there is no checking of each character involved. But I think it's negligible.
c.) little tricky going the reverse(i.e. pad left), I'd have to compensate with the decimal point(by adding 1 to the fixed length) and call REPLACE 2x: (1) To change the decimal pt to the pad char (2) finally change all spaces to the pad char
[code language="T-SQL"]
SELECT REPLACE(REPLACE(STR(@NumToPad, @FixedLength + 1, @FixedLength), '.',@PadChar), SPACE(1), @PadChar)
[/code]
In this case better to use the combo of REPLICATE()+CAST().