Click here to Skip to main content
15,886,746 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hi All,

I need query for auto increment in string value-

I need XS000001,XS000009....XS000099...XS000999,XS009999,XS099999,XS999999

Please help me...
Posted

1 solution

I don't know the source for the values you need to auto-increment, but you should be able to solve the problem using T-SQL code that looks something like this:
SQL
DECLARE @StartAt INT = 0
SELECT 'XS' + REPLACE(STR(1 + @StartAt, 6), SPACE(1), '0')
-- returns XS000001

For the sake of example, suppose your starting value is 745; then the code looks like this:
SQL
DECLARE @StartAt INT = 745
SELECT 'XS' + REPLACE(STR(1 + @StartAt, 6), SPACE(1), '0')
-- returns XS000746

If you are incrementing an integer value in a database table, then the solution might look like this:
SQL
CREATE TABLE #TempCounter (ID INT)
INSERT INTO #TempCounter (ID) VALUES (1)
INSERT INTO #TempCounter (ID) VALUES (2)
INSERT INTO #TempCounter (ID) VALUES (3)
INSERT INTO #TempCounter (ID) VALUES (4)
DECLARE @StartAt INT = (SELECT MAX(ID) FROM #TempCounter)
SELECT 'XS' + REPLACE(STR(1 + @StartAt, 6), SPACE(1), '0')
DROP TABLE #TempCounter
-- returns XS000005

If you are incrementing a string value in a database table, then the solution might look like this:
SQL
CREATE TABLE #TempCounter (ID NVARCHAR(8))
INSERT INTO #TempCounter (ID) VALUES ('XS000100')
INSERT INTO #TempCounter (ID) VALUES ('XS000101')
INSERT INTO #TempCounter (ID) VALUES ('XS000102')
INSERT INTO #TempCounter (ID) VALUES ('XS000103')
DECLARE @StartAt INT = (SELECT CAST(RIGHT(MAX(ID),6) AS INT) FROM #TempCounter)
SELECT 'XS' + REPLACE(STR(1 + @StartAt, 6), SPACE(1), '0')
DROP TABLE #TempCounter
-- returns XS000104

Let me know if this answers your question. My examples assume SQL Server, but perhaps you are using a different platform?
 
Share this answer
 
Comments
Ravindra_IND 17-Oct-15 1:37am    
First of all, I would like to pay thanks for your support, I just need insured's id in these range XS000001,XS000009....XS000099...XS000999,XS009999,XS099999,XS999999.

I working on windows platform, using windows form application, I have one Addnew Insured button when I click on that it must create id between these range automatically.

Thanks ...
Daniel Miller 18-Oct-15 19:27pm    
Sorry my answer was not more helpful. Your question was tagged "SQL" so I thought you were looking for SQL code.

What programming language are you using?

Where are your identifier values stored? In a database or a text file?

How does your code know what identifier values have been generated previously, so that you don't generate any duplicate values?

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