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?
I have always found the following method to be very helpful.
If the field is already a string, this will work
If you want nulls to show as '000'
It might be an integer -- then you would want
For those wanting to update their existing data here is the query:
Simple is that
Like:
I know its old ticket I just thought to share it.
I found this code looking for a solution. Not sure if it works on all versions of MSSQL I have MSSQL 2016.
returns "0023" The 4 in the STR function is the total length including the value. 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 its the same as @Anon post.
For a more dynamic approach try this.