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 w
The safe method:
SELECT REPLACE(STR(n,3),' ','0')
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.
'***'