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
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:
SELECT RIGHT(CONCAT('00',field::text),2)
If the input is also a column of varchar, you can avoid the casting part.
If the field is already a string, this will work
SELECT RIGHT('000'+ISNULL(field,''),3)
If you want nulls to show as '000'
It might be an integer -- then you would want
SELECT RIGHT('000'+CAST(field AS VARCHAR(3)),3)
As required by the question this answer only works if the length <= 3, if you want something larger you need to change the string constant and the two integer constants to the width needed. eg
'0000' and VARCHAR(4)),4
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.
I know this is an old ticket but I just thought I'd share this:
I found this code which provides a solution. Not sure if it works on all versions of MSSQL; I have MSSQL 2016.
declare @value as nvarchar(50) = 23
select REPLACE(STR(CAST(@value AS INT) + 1,4), SPACE(1), '0') as Leadingzero
This returns "0023".
The 4 in the STR function is the total length, including the value. For example, 4, 23 and 123 will all have 4 in STR and the correct amount of zeros will be added. You can increase or decrease it. No need to get the length on the 23.
Edit: I see it's the same as the post by @Anon.
For integers you can use implicit conversion from int to varchar:
SELECT RIGHT(1000 + field, 3)