I have the following table A:
id
----
1
2
12
123
1234
I need to left-pad the id
values with zero\'s:
id
----
0
If someone is still interested, I found this article on DATABASE.GUIDE:
Left Padding in SQL Server – 3 LPAD() Equivalents
In short, there are 3 methods mentioned in that article.
Let's say your id=12 and you need it to display as 0012.
Method 1 – Use the RIGHT() Function
The first method uses the RIGHT() function to return only the rightmost part of the string, after adding some leading zeros.
SELECT RIGHT('00' + '12', 4);
Result:
0012
Method 2 – Use a Combination of RIGHT() and REPLICATE()
This method is almost the same as the previous method, with the only difference being that I simply replace the three zeros with the REPLICATE() function:
SELECT RIGHT(REPLICATE('0', 2) + '12', 4);
Result:
0012
Method 3 – Use a Combination of REPLACE() and STR()
This method comes from a completely different angle to the previous methods:
SELECT REPLACE(STR('12', 4),' ','0');
Result:
0012
Check out the article, there is more in depth analysis with examples.
More efficient way is :
Select id, LEN(id)
From TableA
Order by 2,1
The result :
id
----
1
2
12
123
1234
A simple example would be
DECLARE @number INTEGER
DECLARE @length INTEGER
DECLARE @char NVARCHAR(10)
SET @number = 1
SET @length = 5
SET @char = '0'
SELECT FORMAT(@number, replicate(@char, @length))
This works for strings, integers and numeric:
SELECT CONCAT(REPLICATE('0', 4 - LEN(id)), id)
Where 4
is desired length. Works for numbers with more than 4 digits, returns empty string on NULL
value.
My solution is not efficient but helped me in situation where the values (bank cheque numbers and wire transfer ref no.) were stored as varchar where some entries had alpha numeric values with them and I had to pad if length is smaller than 6 chars.
Thought to share if someone comes across same situation
declare @minlen int = 6
declare @str varchar(20)
set @str = '123'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 000123
set @str = '1234'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 001234
set @str = '123456'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 123456
set @str = '123456789'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 123456789
set @str = '123456789'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: 123456789
set @str = 'NEFT 123456789'
select case when len(@str) < @minlen then REPLICATE('0',@minlen-len(@str))+@str else @str end
--Ans: NEFT 123456789
SQL Server now supports the FORMAT function starting from version 2012, so:
SELECT FORMAT(id, '0000') FROM TableA
will do the trick.
If your id or column is in a varchar
and represents a number you convert first:
SELECT FORMAT(CONVERT(INT,id), '0000') FROM TableA