I have a string that is up to 3 characters long when it's first created in SQL Server 2008 R2.
I would like to pad it with leading zeros, so if its original value was '1' then the new value would be '001'. Or if its original value was '23' the new value is '023'. Or if its original value is '124' then new value is the same as original value.
I am using SQL Server 2008 R2. How would I do this using T-SQL?
Wrote this because I had requirements for up to a specific length (9). Pads the left with the @pattern ONLY when the input needs padding. Should always return length defined in @pattern.
Returns 1234input
The safe method:
This has the advantage of returning the string
'***'
for n < 0 or n > 999, which is a nice and obvious indicator of out-of-bounds input. The other methods listed here will fail silently by truncating the input to a 3-character substring.Although the question was for SQL Server 2008 R2, in case someone is reading this with version 2012 and above, since then it became much easier by the use of FORMAT.
You can either pass a standard numeric format string or a custom numeric format string as the format argument (thank Vadim Ovchinnikov for this hint).
For this question for example a code like
outputs
Here is a variant of Hogan's answer which I use in SQL Server Express 2012:
Instead of worrying if the field is a string or not, I just
CONCAT
it, since it'll output a string anyway. Additionally if the field can be aNULL
, usingISNULL
might be required to avoid function gettingNULL
results.For integers you can use implicit conversion from int to varchar:
Use this function which suits every situation.
Sample output