Click here to Skip to main content
15,888,062 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, How to increment and print a variable in the format of 001.
I can print only 1, but not zeros before to 1.
Any help is appreciated.

Expected:
001
002
003
004...
Posted
Comments
Maciej Los 15-May-13 6:15am    
What you mean: how to increament?
Did you try to search for it on CP?
Please, be more specific and provide more details.

SQL
SELECT replicate('0',3-LEN(Id)) + CONVERT(VARCHAR,Id) From TblNm

Or
SQL
DECLARE @Id INT
SET @Id = 1 --change id = 11 or 111
PRINT replicate('0',3-LEN(@Id)) + CONVERT(VARCHAR,@Id)

Happy Coding!
:)
 
Share this answer
 
v3
Comments
Maciej Los 15-May-13 6:48am    
+5
Aarti Meswania 15-May-13 6:50am    
Thank you! :)
Please, see my comment. When you reply me, i'll update my answer.

Please, test it:
SQL
;WITH PseudoNumbers AS
(
	SELECT 1 AS MyVal, CAST('00001' AS NVARCHAR(5)) AS PseudoNumber
	UNION ALL
	SELECT MyVal + 1 AS MyVal, CAST(LEFT('00000', LEN('00000')-LEN(CAST(MyVal+1 AS NVARCHAR(5)))) +  CAST(MyVal+1 AS NVARCHAR(5)) AS NVARCHAR(5)) AS PseudoNumber
	FROM PseudoNumbers
	WHERE MyVal <100
)
SELECT *
FROM PseudoNumbers
--OPTION (MAXRECURSION 0)
--uncomment above line, if you want to get more than 100 records ;)
--Thank you, Code-Hunt ;) for your comment



Results:
M.. PseudoNumber
1   00001
2   00002
3   00003
4   00004
5   00005
...
100 00100


More:
Using Common Table Expressions[^]
 
Share this answer
 
v3
Comments
[no name] 15-May-13 6:50am    
@Maciej Los: +5 :)
Maciej Los 15-May-13 6:52am    
Thank you ;)
[no name] 15-May-13 6:51am    
@Maciej Los: But one question..what will be the updated solution for 999
Maciej Los 15-May-13 6:54am    
It's simple. Change WHERE statement inside CTE loop to WHERE MyVal<1000<code> ;)
[no name] 15-May-13 6:58am    
i tried that but i m getting the below error

The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
SQL has no built in way to format numbers with leading zeros. But it isn't complicated:
SQL
SELECT RIGHT('00'+ CONVERT(VARCHAR,Id),3) FROM myTable;
 
Share this answer
 
v2
Comments
Maciej Los 15-May-13 6:47am    
+5
You can try the While loop in SQL with Some increment and concatenation.
Please try the following Code

DECLARE @intFlag VARCHAR(20)
 SET @intFlag =0
WHILE (@intFlag <=998)
BEGIN
SET @intFlag = @intFlag + 1
SET @intFlag='00'+@intFlag
PRINT @intFlag
END
GO
 
Share this answer
 
v2
Comments
[no name] 15-May-13 6:35am    
Not the good one...after its touching 2/3 digits..it should not show that many 0's...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900