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?
Here's a more general technique for left-padding to any desired width:
However, if you're dealing with negative values, and padding with leading zeroes, neither this, nor other suggested technique will work. You'll get something that looks like this:
[Probably not what you wanted]
So … you'll have to jump through some additional hoops Here's one approach that will properly format negative numbers:
One should note that the
convert()
calls should specify an[n]varchar
of sufficient length to hold the converted result with truncation.I had similar problem with integer column as input when I needed fixed sized varchar (or string) output. For instance, 1 to '01', 12 to '12'. This code works:
If the input is also a column of varchar, you can avoid the casting part.